这是我收到的错误消息:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextBoolean(Scanner.java:1893)
at calcSums.main(calcSums.java:24)
这是我的代码:
import java.util.Scanner;
public class calcSums
{
public static void main(String[] args)
{
calcSum:{
Boolean again = Boolean.valueOf("y");
Scanner keyboard = new Scanner (System.in);
double number;
double sum = 0;
System.out.println("Enter a positive number");
number = keyboard.nextDouble();
while (number > 0)
{
sum = sum + number;
System.out.println("Enter another positive number, enter 0 or negative to end");
number = keyboard.nextDouble();
}
System.out.println("The sum is: ");
System.out.println(sum);
System.out.println("Would you like to find another sum? (y/n)");
again = keyboard.nextBoolean();
if (again.equals("y")) {
break calcSum; }
}
}
}
由于我不使用.equals,并且在允许我执行我认为已完成的代码时,我之前收到关于如何实现if语句的错误消息,然后当我尝试循环访问再次阻止它给了我错误消息
答案 0 :(得分:0)
这是因为您不能输入“ y”作为布尔值。布尔值的字符串表示形式为“ true”或“ false”。
只需像这样在字符串中更改再次变量:
String again = new String();
... //Your other code
System.out.println("Would you like to find another sum? (y/n)");
again = keyboard.nextLine();
if (again.equalsIgnoreCase("y")) {
break calcSum;
}
还要考虑使用另一个while循环而不是您的calcsum-label。
String again = new String("y");
while(again.equalsIgnoreCase("y"){
... //Your other code
System.out.println("Would you like to find another sum? (y/n)");
//again = keyboard.nextLine();
again = new Scanner(System.in).nextLine();
}