如果这些条件都不满足或输出已打印,则它将返回要求用户输入新值。如果在输入阶段的任何时刻用户输入单词"0";退出";然后结束程序
让我的程序遵循这些条件是我解决问题之前唯一缺少的部分。在一开始就有一个while循环,条件与字符串输入"1"一样长;退出";被输入,它将结束,这是我一直试图做的,但一直失败。
我们的课刚开始,我们甚至还没有涉及方法或OOP。我们的教授只教我们scanner system.in和.next(数据类型(方法,所以我认为scanner类的其他方法一直在我的脑海中寻找解决方案。
这是我的程序的输入阶段:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please give three numbers");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int num3 = sc.nextInt();
System.out.println("Choose the temperature unit of the three numbers.");
System.out.println("Enter 1 for Celsius, 2 for Fahrenheit and 3 for Kelvin");
int tempUnit = sc.nextInt();
switch (tempUnit) {
case (1) -> System.out.println("Celsius was chosen.");
case (2) -> System.out.println("Fahrenheit was chosen.");
case (3) -> System.out.println("Kelvin was chosen.");
}
System.out.println("Choose the temperature unit you want to convert it into.");
System.out.println("Enter 1 for Celsius, 2 for Fahrenheit and 3 for Kelvin");
int chosenTemp = sc.nextInt();
switch (chosenTemp) {
case (1) -> System.out.println("Celsius was chosen.");
case (2) -> System.out.println("Fahrenheit was chosen.");
case (3) -> System.out.println("Kelvin was chosen.");
}
我试着按照你们告诉我的想出一些东西,这就是我想出的?
if (!sc.hasNextInt()) {
String end = sc.nextLine();
if (end.equalsIgnoreCase("Quit")) {
System.exit(0);
它起了作用,但我觉得这不是你们让我做的。你能给我举个例子吗?我读到你不是这样设置";退出";有人能教我怎么做吗?
我想你想要实现以下
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("Please give three numbers");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int num3 = sc.nextInt();
System.out.println("Choose the temperature unit of the three numbers.");
System.out.println("Enter 1 for Celsius, 2 for Fahrenheit, 3 for Kelvin and 4 for Quit");
int tempUnit = sc.nextInt();
switch (tempUnit) {
case 1 :
System.out.println("Celsius was chosen.");
break;
case 2 :
System.out.println("Fahrenheit was chosen.");
break;
case 3 :
System.out.println("Kelvin was chosen.");
break;
case 4 :
System.out.println("Quit");
System.exit(0);
}
}