我得到的结果:
Enter a number :
5
Enter another number :
4
What do you want to perform on these numbers?
You have entered a wrong action, please try again
我的代码在哪里出错?
import java.util.Scanner;
public class App {
public static void main(String[] args) {
double num1, num2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number : ");
num1 = sc.nextDouble();
System.out.println("Enter another number : ");
num2 = sc.nextDouble();
System.out.println("What do you want to perform on these numbers? ");
String word = sc.nextLine();
sc.close();
double result = 0;
switch (word) {
case "Addition":
result = num1 + num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Subtraction":
result = num1 - num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Multiplication":
result = num1 * num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Division":
result = num1 / num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
default:
System.out.println("You have entered a wrong action, please try again ");
break;
}
}
}
答案 0 :(得分:0)
您是否可以像下面那样更改代码:
System.out.println("What do you want to perform on these numbers? ");
sc.nextLine(); // ADD THIS LINE
String word = sc.nextLine();
这里的问题是num2 = sc.nextDouble();
的换行符不被使用。
下面是我使用的代码:
public static void main(String args[]) throws Exception {
// A1Pattern.printPattern(26);
double num1, num2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number : ");
num1 = sc.nextDouble();
System.out.println("Enter another number : ");
num2 = sc.nextDouble();
System.out.println("What do you want to perform on these numbers? ");
sc.nextLine();
String word = sc.nextLine();
sc.close();
double result = 0;
switch (word) {
case "Addition":
result = num1 + num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Subtraction":
result = num1 - num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Multiplication":
result = num1 * num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
case "Division":
result = num1 / num2;
System.out.println(num1 + " " + word + " " + num2 + " : " + result);
break;
default:
System.out.println("You have entered a wrong action, please try again ");
break;
}
}
输出:
输入数字: 1个 输入另一个号码: 2 您想对这些数字执行什么操作? 减法 1.0减法2.0:-1.0
答案 1 :(得分:0)
不要在第15行使用sc.nextline()
。该程序现在将等待您的输入,然后继续。
答案 2 :(得分:0)
java.util.Scanner.next()方法从此扫描器中查找并返回下一个完整令牌。
使用scanner.next()而不是scanner.nextLine()。