Do-While循环不循环 – Java

huangapple go评论70阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月6日 09:06:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63275462.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定