Java do while循环只执行2次运行
我试图做一个简单的程序,用户选择一个数字1,2,3进行简单的计算。除非用户在菜单上被询问时键入“0”,否则程序将继续运行。只要用户选择1、2或3,就会显示相同的菜单。如果用户选择0,程序将终止 我的守则如下:Java do while循环只执行2次运行,java,do-while,Java,Do While,我试图做一个简单的程序,用户选择一个数字1,2,3进行简单的计算。除非用户在菜单上被询问时键入“0”,否则程序将继续运行。只要用户选择1、2或3,就会显示相同的菜单。如果用户选择0,程序将终止 我的守则如下: import java.util.Scanner; public class QuadraticSolving { public static void main(String[] args) { // Declarations int user; double
import java.util.Scanner;
public class QuadraticSolving {
public static void main(String[] args) {
// Declarations
int user;
double a;
double b;
double c;
int num1;
int num2;
Scanner in = new Scanner(System.in);// Create scanner in
do{
System.out.print("Press 0 to exit, 1 for Multiplication Solving, 2 for Sum or 3 for Print Message:");// main menu
user = in.nextInt();
}
while(user == 0);
{
if(user == 1)// multiplication solver
{
System.out.print("Enter a:");
a = in.nextDouble();
System.out.print("Enter b:");
b = in.nextDouble();
System.out.print("Enter c:");
c = in.nextDouble();
System.out.println(a*b*c);
}
else if(user == 2)// addition
{
System.out.print("Enter an integer:");
num1 = in.nextInt();
System.out.print("Enter another integer:");
num2 = in.nextInt();
System.out.println(num1 + num2);
// System.out.println(allSum(num1,num2));
System.out.print("");
}
else if (user == 3)// welcome statement
{
System.out.println("Welcome to IT");
}
else
{
System.out.println("Bye");
break;
}
System.out.print("Press 0 to exit, 1 for Multiplication Solving, 2 for Sum or 3 for Print Message:");
user = in.nextInt();
}
}
在第一次运行菜单之后,它工作得非常好。在第二次运行期间,无论您选择什么选项,它都会终止程序
每当我为所有跑步输入“0”时,它就会变成一个无休止的循环。我能阻止它的唯一方法是结束代码的执行。
我不明白为什么程序只在第一次运行时运行良好,而在第二次运行时它会自行终止。而且,我不明白为什么当用户输入“0”时,它会进入一个无休止的循环。有没有解释为什么会发生这种情况?抱歉打扰了,我是编程新手。感谢当用户键入0时,它进入一个无休止的循环,因为while表达式正在检查键入的数字是否等于0而不是不同 它第一次运行正常,因为之后运行的代码没有重复,它只执行一次,代码应该在这里
do {
.
. // Here you scan
. // Here you paste the logic
.
} while (user != 0);
当…时做{…}。。。;这就是循环。后面的代码块不是任何循环的一部分,不管大括号是什么。do。。。而如果条件为false,则每隔一个循环就会中止。此外,您可能希望在do之后使用大代码块。存在几个问题,包括在实际循环之后错误放置大括号。关于Scanner.next,请看这里:整个if-else语句都在while循环中。在发布这些类型的问题之前,您应该尝试彻底调试。在do-while或if-else循环中放置一个断点可能会为您回答这个问题。否则,其他评论是正确的