英文:
Do-While Loop not looping - Java
问题
以下是翻译好的代码部分:
我在下面的Java代码中遇到了问题。我希望循环在输入数字“-100”时停止,但实际上只要输入任何数字,循环就会停止。我正在学习如何使用Java,所以可能有很多错误。
public class Main {
public static void main(String[] args){
Scanner keyboard = new Scanner (System.in);
String num = "";
do {
System.out.println("请输入一个数字:");
int n = keyboard.nextInt();
System.out.println("您输入的数字是:" + n);
System.out.println("------------------------");
} while ("-100".equals(num));
}
}
如果您需要进一步的帮助,请随时告诉我。
英文:
I am having a problem with my java code below. I want the loop to stop when the number "-100" but it stops as soon as you enter any number. I'm just learning how to use java so there could be plenty of mistakes here.
public static void main(String[] args){
Scanner keyboard = new Scanner (System.in);
String num = "";
do {
System.out.println("Enter a number: ");
int n = keyboard.nextInt();
System.out.println("The number you entered is: " +n);
System.out.println("------------------------");
} while ("-100".equals(num));
}
}
答案1
得分: 3
num
始终是空字符串,因为您从未更改 num
的值。您更新 n
。这是我将基于的循环条件。例如,
Scanner keyboard = new Scanner(System.in);
int n;
do {
System.out.println("输入一个数字:");
n = keyboard.nextInt();
System.out.println("您输入的数字是:" + n);
System.out.println("------------------------");
} while (n != -100);
也就是说,当 n
不等于 -100
时执行循环。
英文:
num
is always the empty string, because you never change the value of num
. You update n
. Which is what I would base the loop on. Like,
Scanner keyboard = new Scanner(System.in);
int n;
do {
System.out.println("Enter a number: ");
n = keyboard.nextInt();
System.out.println("The number you entered is: " + n);
System.out.println("------------------------");
} while (n != -100);
That is, do loop while n
is not -100
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论