gpt4 book ai didi

java - 在 Java 中用字符串重复整个循环很困难

转载 作者:太空宇宙 更新时间:2023-11-04 10:08:04 27 4
gpt4 key购买 nike

我是编程新手,我开始练习 Java。在我的练习中,我要求编写一个程序来计算并打印出数字的数字之和。然后它打印出和数的所有除数。

问题是,在那之后,我需要询问用户是否想尝试另一个号码,当用户回答"is"时,我无法重新启动程序。谢谢你,对不起我的英语!

//Introduction
System.out.println("\nWelcome to our Calculation Program!\n----------------------------------------");



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("yes")) {
System.out.println("Enter a number with a most 7-digits:");

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 + " ");

} if (choice.equals("no")) {

System.out.println("Thanks and Have a Great Day!");

最佳答案

您只需完成循环即可重新启动

        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

关于java - 在 Java 中用字符串重复整个循环很困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52693003/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com