Java 如何在 while 循环中输入 if 语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38670004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:30:19  来源:igfitidea点击:

How can I input an if statement inside a while loop?

javaif-statementwhile-loopnested

提问by Rudy

import java.util.Scanner;
public class ex11 
{
static Scanner type=new Scanner(System.in);
    public static void main(String args[])
    {
        int fact=1;
        System.out.println("Enter a natural number ");
        int num=type.nextInt();

        int i=1;
        while(i<=num)
        {
            fact*=i;
            i++;    
        }
        System.out.println("Factorial of number " + num + " is " + fact);
    }
}

I'm trying to place a conditional statement inside the while loop. The condition is to test for would be that of, if num is a negative number, S.O.P.("You entered a negative #");in other words,

我试图在 while 循环中放置一个条件语句。条件是要测试的是,如果 num 是负数,S.O.P.("You entered a negative #");换句话说,

if(num<0)
    S.O.P.("You entered a negative #");

However it doesn't print it properly.

但是它不能正确打印。

采纳答案by Arthur

If you check inside the loop then it will not work it will still multiply the fact. You need to make sure that the numis not negative before you start the while loop.

如果您在循环内部进行检查,则它将不起作用,它仍然会乘以fact. num在开始 while 循环之前,您需要确保 the不是负数。

int num = 0;
do {
    if (num<0){
        System.out.println("You printed out a negative number");
    }
    System.out.println("Enter a natural number ");
    int num=type.nextInt();
} while (num<0);

Also on a side note you should probably close your scanners when you are done using them.

另外,在使用完扫描仪后,您可能应该关闭它们。

回答by Stephen C

To answer your question .... like this:

回答你的问题......像这样:

int i = 1;     // HERE
while (i <= num) {
    if (num < 0) {
        System.out.println("You entered a negative #");
    }
    fact *= i;
    i++;    
}

However that is not going to work.

然而,这是行不通的。

Suppose that "num" that you read is less than zero.

假设您读取的“num”小于零。

  • At the statement labeled "HERE", we set "i" to one.
  • In the next statement, we test "i < num".
  • Since "num" is less than zero, that test gives "false" and we skip over the entire loop!
  • 在标记为“HERE”的语句中,我们将“i”设置为 1。
  • 在下一个语句中,我们测试“i < num”。
  • 由于“num”小于零,该测试给出“false”,我们跳过整个循环!

That means that your conditional statement in the loop body would not be executed ... if "num" is less than zero.

这意味着您在循环体中的条件语句将不会被执行……如果“num”小于零。

Since this is obviously homework, I will leave it to you to figure out what you shouldbe doing here. But (HINT!) it is not putting the conditional inside the loop.

由于这显然是家庭作业,我将留给您弄清楚您应该在这里做什么。但是(提示!)它没有将条件放入循环中。

(Please note: I have corrected a number of style errors in your code. Compare your original version with mine. This is how you shouldwrite Java code.)

(请注意:我已经在你的代码纠正一些错误的风格与我的比你原来的版本,这是你如何。应该编写Java代码。)

回答by Ryan

The question is hard to understand but from what i read it appears you want a loop to run until a value is entered that meets your pre-condition of being positive

这个问题很难理解,但从我读到的内容来看,您似乎希望循环运行,直到输入一个满足您为正的先决条件的值

System.out.println("Enter a non negative number :: ");
int num = type.nextInt();
while(num < 0){
    System.out.println("The number you entered was negative!");
    System.out.println("Enter a non negative number :: ");
    num = type.nextInt();
}

Loops like this are crucial to making sure the data that you are using is within the pre-condition of your operation which could cause DivideByZeroerrors or other problems. This loop should be placed before you ever use the value of numso you can make sure it is within context of your program.

像这样的循环对于确保您使用的数据在您的操作的前提条件内至关重要,这可能会导致DivideByZero错误或其他问题。这个循环应该在你使用值之前放置,num这样你就可以确保它在你的程序上下文中。

回答by Kasun Siyambalapitiya

The problem is that if the numis negative, it won't go inside the while loopthat is because before the while loopyou have initialize i=1, since any negative number is lesser than 1the condition for while loopbecome false. If you want to check whether numis negative insert the if conditionbefore the while loopas follows

问题是,如果num是负数,它不会进入 ,while loop这是因为在while loopinitialize之前i=1,因为任何负数都小于变为假1的条件while loop。如果要检查是否num为负数if condition,请while loop按如下方式在前面插入

   import java.util.Scanner;
    public class ex11 
    {
    static Scanner type=new Scanner(System.in);
    public static void main(String args[])
    {
        int fact=1;
        System.out.println("Enter a natural number ");
        int num=type.nextInt();

        int i=1;

         if(num < 0) {
           System.out.println("You entered a negative #");
          }
         else{

              while(i<=num)
              {
               fact*=i;
               i++;    
               }
        System.out.println("Factorial of number " + num + " is " + fact);
       }
    }

}

回答by progyammer

You basically have to check whether the number is less than 0. This is to be done while taking the input. You can just take the input inside a while loop in this manner:

您基本上必须检查数字是否小于 0。这是在输入时完成的。您可以通过这种方式在 while 循环中获取输入:

System.out.println("Enter a natural #");
while(true){ //loop runs until broken
    num = type.nextInt();
    if(num>=0)
        break;
    System.out.println("Wrong input. Please enter a positive number");
}

The program control breaks out of the loop if num>=0, i.e., positive, else, it continues to the next part of the loop and displays the error message and takes the input again.

程序控制在 if 时跳出循环num>=0,即为正,否则,它继续执行循环的下一部分并显示错误消息并再次接受输入。

Please note that natural numbers are the ones >= 1. In your program, you are actually trying to input a whole number which is >= 0.

请注意,自然数是 >= 1 的数。在您的程序中,您实际上是在尝试输入一个 >= 0 的整数。