Java 循环顺序停止
我将代码放入do-while循环中。它询问用户想要哪个菜单选项,并为他们计算公式。代码应该一直运行,直到用户点击4,这是退出选项,但在一个序列后停止。我不知道我需要更改或添加什么,所以它继续进行Java 循环顺序停止,java,loops,while-loop,Java,Loops,While Loop,我将代码放入do-while循环中。它询问用户想要哪个菜单选项,并为他们计算公式。代码应该一直运行,直到用户点击4,这是退出选项,但在一个序列后停止。我不知道我需要更改或添加什么,所以它继续进行 import java.util.Scanner; import java.text.DecimalFormat; class Lab5 { public static void main(String[] args) //header of the main method {
import java.util.Scanner;
import java.text.DecimalFormat;
class Lab5
{
public static void main(String[] args) //header of the main method
{
Scanner in = new Scanner(System.in);
int choice;
int rem = 0;
int num;
do
{
//user prompt
System.out.print("Choose from the following menu\n1) Calculate the sum of integers 1 to m\n2) Factorial of a number\n3) Repeat the first number\n4) Quit\n:");
choice = in.nextInt();
switch(choice)
{
case 1:
int m, sum =0;
int i = 1;
System.out.print("Enter the number:");
m = in.nextInt();
while (i <= m)
{
sum=sum+i;
i++;
}
System.out.print("The sum of:" + m + ' ' + "is" + ' ' + sum);
break;
case 2:
int number, fact =1;
System.out.print("Enter the number:");
number = in.nextInt();
i=1;
for (int factor = 2; factor <= number; factor++)
{
fact = fact*factor;
}
System.out.print("The Factorial of +:" + number + ' ' + "is" + ' ' + fact);
break;
case 3:
System.out.print("Enter the number:");
num = in.nextInt();
while(num!=0)
{
rem = num%10;
num = num/10;
}
System.out.print("The leftmost digit is:" + rem);
break;
default:
break;
}
} while (choice == '4');
System.out.print(" ");
}
}
import java.util.Scanner;
导入java.text.DecimalFormat;
Lab5类
{
publicstaticvoidmain(String[]args)//main方法的头
{
扫描仪输入=新扫描仪(系统输入);
智力选择;
int-rem=0;
int-num;
做
{
//用户提示
System.out.print(“从以下菜单中选择\n1)计算整数1到m的总和\n2)数字的阶乘\n3)重复第一个数字\n4)退出\n:”;
choice=in.nextInt();
开关(选择)
{
案例1:
int m,和=0;
int i=1;
系统输出打印(“输入号码:”);
m=in.nextInt();
while(i您将其编写为do…while(choice=='4')
,这意味着只有当用户输入4时,它才会继续
听起来你想要选择!='4'
也'4'
或4
?值来自nextInt()
而不是char
@John3136:仅在逻辑时寻址。