英文:
Application throws InputMismatchException when string is assigned to double
问题
You can use the contains
method in Java to check if a string contains whitespaces. Here's the relevant code with the translation:
// 检查输入字符串是否包含空格
if (name.contains(" ")) {
// 处理包含空格的情况
// ...
}
This code will help you check if the name
string contains any whitespaces.
英文:
I am writing a program where I need to check if a string (name
) contains any whitespaces or not.
Here's part of my program :
public static void main()
{
Scanner sc = new Scanner(System.in) ;
String name = "" ;
boolean error = false ;
do {
if(error) System.out.println("Sorry, error. Try again") ;
error = false ;
System.out.print("Enter your name : ") ;
name = sc.next() ;
if(name=="") error = true ;
} while(error) ;
double amount = 0.00 ;
do {
if(error) System.out.println("Sorry, error. Try again") ;
error = false ;
System.out.print("Enter amount of purchase : ") ;
amount = sc.nextDouble() ;
if(amount<=1) error = true ;
} while(error) ;
}
}
For checking errors in the name
string input, I need to check if the string contains any whitespaces or not because otherwise java.lang.InputMismatchException
is thrown when it accepts amount
(and when the entered name
contains whitespace with another string).
Is there any predefined function that does this?
答案1
得分: 1
以下是您要翻译的内容:
你可以使用以下方法来确定一个 String
是否包含空格字符。
boolean containsSpace(String string) {
for (char character : string.toCharArray()) {
switch (character) {
case ' ', '\t', '\n', '\r', '\f' -> {
return true;
}
}
}
return false;
}
另外,你需要使用 String.equals
方法来测试 name
值,而不是使用 ==
相等运算符。
if (name.equals("")) error = true;
此外,main
方法需要一个单一的 String
数组参数或 String
可变参数才能有效。
public static void main(String[] args)
以下是我如何实现这个任务的快速演示。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name;
while (true) {
System.out.print("Name: ");
name = scanner.nextLine();
if (!containsSpace(name))
break;
System.out.println("Name contains white-space. Re-enter.");
}
double amount;
while (true) {
System.out.print("Amount: ");
try {
amount = Double.parseDouble(scanner.nextLine());
break;
} catch (NumberFormatException exception) {
System.out.println("Invalid amount. Re-enter.");
}
}
System.out.printf("Name is '%s'%n", name);
System.out.printf("Amount is %,f%n", amount);
}
英文:
You can use the following method to determine if a String
contains a white-space character.
boolean containsSpace(String string) {
for (char character : string.toCharArray()) {
switch (character) {
case ' ', '\t', '\n', '\r', '\f' -> {
return true;
}
}
}
return false;
}
Also, you're going to want to test the name
value using the String.equals
method, as opposed to the ==
equality operator.
if (name.equals("")) error = true;
Furthermore, the main
method requires a single String
array, or String
varargs parameter, to be valid.
public static void main(String[] args)
Here is a quick demonstration of how I would implement the task.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name;
while (true) {
System.out.print("Name: ");
name = scanner.nextLine();
if (!containsSpace(name))
break;
System.out.println("Name contains white-space. Re-enter.");
}
double amount;
while (true) {
System.out.print("Amount: ");
try {
amount = Double.parseDouble(scanner.nextLine());
break;
} catch (NumberFormatException exception) {
System.out.println("Invalid amount. Re-enter.");
}
}
System.out.printf("Name is '%s'%n", name);
System.out.printf("Amount is %,f%n", amount);
}
答案2
得分: 1
Sure, here are the translated parts:
我正在编写一个程序,需要检查字符串(名称)是否包含任何空格。
所以没有预定义的函数吗?
当然有 - isWhitespace,
还有可能考虑使用trim()方法,
从用户输入中去除前导和尾随空格:name = scanner.next().trim();
boolean containsSpace(String string) {
for (char character : string.toCharArray()) {
if (Character.isWhitespace(character)) {
return true;
}
}
return false;
}
至于你的问题的第二部分 - 将"amount"作为double获取,
我建议拆分为两个简单的函数,遵循单一职责原则,以提高可维护性和可测试性。
然后,将方法getDouble(String string)放入一个专用的类和包中,假设为:myproject.common.Numbers
整个程序将包含如下方法:
public static void main(String[] args) {
final var instance = new StackOverflow();
instance.parseNameAndAmount();
}
void parseNameAndAmount() {
Scanner scanner = new Scanner(System.in);
final var name = getName(scanner);
final var amount = getAmount(scanner);
scanner.close();
print("Name is %s".formatted(name));
print("Amount is %s".formatted(amount));
}
String getName(Scanner scanner) {
String name;
do {
print("Enter a name with no spaces: ");
name = getName(scanner.nextLine().trim());
} while (name == null);
return name;
}
String getName(String string) {
if (string == null || string.isEmpty()) {
return null;
}
if (containsSpace(string)) {
return null;
}
return string;
}
boolean containsSpace(String string) {
for (char character : string.toCharArray()) {
if (Character.isWhitespace(character)) {
return true;
}
}
return false;
}
double getAmount(Scanner scanner) {
Double amount;
do {
print("Enter amount of purchase (valid number): ");
amount = getDouble(scanner.nextLine().trim());
} while (amount == null);
return amount;
}
Double getDouble(String string) {
if (string == null) {
return null;
}
try {
return Double.valueOf(string);
} catch (NumberFormatException e) {
return null;
}
}
void print(String string) {
System.out.println(string);
}
正如我提到的,为了测试性和可维护性,
其中一个测试可能如下所示,当然要彻底测试,
需要进行更多的测试。
@Test
void getDouble_When_NegativeWithExponent() {
// 给定
final var given = "-12.45E9";
// 当
final var actual = stackOverflow.getDouble(given);
// 那么
assertThat(actual)
.isNotNull()
.isNegative();
}
Please note that I've kept the code formatting in its original structure for clarity. If you have any specific questions or need further assistance, feel free to ask.
英文:
> I am writing a program where I need to check if a string (name) contains any whitespaces or not.
> so there isn't any predefined functions?
Of course, there is - isWhitespace,<br>
plus the trim() method might be considered,<br>
to remove leading and trailing spaces from the user input: name = scanner.next().trim();
boolean containsSpace(String string) {
for (char character : string.toCharArray()) {
if (Character.isWhitespace(character)) {
return true;
}
}
return false;
}
And the second part of your problem - to get the "amount" as a double,
I would split into two simplistic functions to follow single responsibility principle and improve maintainability and testability.
And I will put method getDouble(String string) into a dedicated class, and package, let say: myproject.common.Numbers
So the whole program will consist methods like this:
public static void main(String[] args) {
final var instance = new StackOverflow();
instance.parseNameAndAmount();
}
void parseNameAndAmount() {
Scanner scanner = new Scanner(System.in);
final var name = getName(scanner);
final var amount = getAmount(scanner);
scanner.close();
print("Name is %s".formatted(name));
print("Amount is %s".formatted(amount));
}
String getName(Scanner scanner) {
String name;
do {
print("Enter a name with no spaces: ");
name = getName(scanner.nextLine().trim());
} while (name == null);
return name;
}
String getName(String string) {
if (string == null || string.isEmpty()) {
return null;
}
if (containsSpace(string)) {
return null;
}
return string;
}
boolean containsSpace(String string) {
for (char character : string.toCharArray()) {
if (Character.isWhitespace(character)) {
return true;
}
}
return false;
}
double getAmount(Scanner scanner) {
Double amount;
do {
print("Enter amount of purchase (valid number): ");
amount = getDouble(scanner.nextLine().trim());
} while (amount == null);
return amount;
}
Double getDouble(String string) {
if (string == null) {
return null;
}
try {
return Double.valueOf(string);
} catch (NumberFormatException e) {
return null;
}
}
void print(String string) {
System.out.println(string);
}
As I mentioned testability and maintainability,
one of the tests might look like this, of course to be thorough,
more tests needs to be done.
@Test
void getDouble_When_NegativeWithExponent() {
// Given
final var given = "-12.45E9";
// when
final var actual = stackOverflow.getDouble(given);
// Then
assertThat(actual)
.isNotNull()
.isNegative();
}
答案3
得分: 0
如果你想读取一个浮点数,你必须明确地使用 Scanner.nextDouble()
进行请求。next()
返回一个字符串。在Java中,你不能将一个字符串赋值给一个数字。
英文:
If you want to read a floating point number you have to explicitly ask for it using Scanner.nextDouble(). next() returns a String. You can not assign a string to a number in Java.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论