3 回答
TA贡献2039条经验 获得超7个赞
while (input > 0);
这将进入无限循环。我想你把一个;而不是{.
应该 while (input > 0){
编辑:
System.out.println("\nWelcome to our Calculation Program!\n----------------------------------------");
while(true){
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
int sum = 0;
while (input > 0) {
int add = input % 10;
sum = sum + add;
input = input / 10;
}
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
}
System.out.println("\n\nDo you want to try another number?");
Scanner mykeyboard2 = new Scanner(System.in);
String choice = mykeyboard2.nextLine();
if (choice.equals("no")) {
break;
}
}
TA贡献1802条经验 获得超4个赞
实现它的最简单方法是使用您的选择变量来控制循环条件:
System.out.println("\nWelcome to our Calculation Program!\n----------------------------------------");
String choice = "yes";
while(choice.equals("yes")) {
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
int sum = 0;
while (input > 0) {
int add = input % 10;
sum = sum + add;
input = input / 10;
}
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
System.out.println("\n\nDo you want to try another number?");
Scanner mykeyboard2 = new Scanner(System.in);
choice = mykeyboard2.nextLine();
}
System.out.println("Thanks and Have a Great Day!");
TA贡献1859条经验 获得超6个赞
你只需要让循环重新开始
System.out.print("Enter a number with at most 7-digits:");
int input = mykeyboard.nextInt();
while(input != -1){
int sum = 0;
int add = input % 10;
sum = sum + add;
input = input / 10;
System.out.println("Sum of the digits of your input is: " + sum);
System.out.print("The divisors of " + sum + " are as follows: " );
for (int counter = 1; sum >= counter; counter++) {
if (sum % counter == 0)
System.out.print(counter + " ");
System.out.print("Do you want another number? If you dont type -1: ");
input = mykeyboard.nextInt();
}
代码会一直运行直到用户输入 -1
添加回答
举报