如何解决试图了解退出,循环,方法以及“如果与其他” [JAVA]
大家好,我的代码需要帮助。我试图了解如何使用方法,循环,if-else语句和退出代码。因此,我正在根据用户选择写一个简单的计算,但是现在我不知道当用户输入的数字不是数字(表示不允许使用字母)时,如何使输入回读。 em>,它将继续返回选项,直到用户输入正确的选项1或2。
请让我知道我是否犯了任何错误,或者是否有办法进一步简化此代码。
想要这样的输出:-
[1] Calculation [2] Exit Your choice: a Please choose only 1 or 2 [1] Calculation [2] Exit Your choice: 1 Enter 1st number: 1 Enter 2nd number: 1 Total: 2
代码:-
import java.util.Scanner;
public class Testing {
int ans;
boolean Loop = true;
public void SimpleCalculation() {
Scanner input = new Scanner(System.in);
while (Loop) {
System.out.println("[1] Calculation ");
System.out.println("[2] Exit");
System.out.print("Your choice: ");
ans = input.nextInt();
if (ans == 1) {
System.out.print("Enter 1st number: ");
int number1 = input.nextInt();
System.out.print("Enter 2nd number: ");
int number2 = input.nextInt();
int result = number1 + number2;
System.out.println("Total: " + result);
} else if (ans == 2) {
System.out.println("Thank you");
input.close();
break;
} else {
System.out.println("Please choose only 1 or 2");
}
}
System.exit (0);
}
public static void main(String[] args) {
Testing t = new Testing();
t.SimpleCalculation();
}
}
解决方法
我已经更新了您的代码:
public class Testing {
public static void SimpleCalculation() {
boolean Loop = true;
Scanner input = new Scanner(System.in);
while (Loop) {
System.out.println("[1] Calculation ");
System.out.println("[2] Exit");
System.out.print("Your choice: ");
while(!input.hasNextInt()) {
System.out.println("Please choose only 1 or 2");
input.nextLine();
continue;
}
int ans = input.nextInt();
if (ans == 1) {
System.out.print("Enter 1st number: ");
int number1 = input.nextInt();
System.out.print("Enter 2nd number: ");
int number2 = input.nextInt();
int result = number1 + number2;
System.out.println("Total: " + result);
} else if (ans == 2) {
System.out.println("Thank you");
input.close();
break;
} else {
System.out.println("Please choose only 1 or 2");
}
}
}
public static void main(String[] args) {
SimpleCalculation();
}
}
输出:
[1] Calculation
[2] Exit
Your choice: a
Please choose only 1 or 2
[1] Calculation
[2] Exit
Your choice: 1
Enter 1st number: 1
Enter 2nd number: 2
Total: 3
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。