Java while循环括号函数

标签 java loops while-loop

我的代码:

import java.util.*;

public class test
{

    public static void main(String[] args)
    {
        Scanner Input = new Scanner(System.in);

        System.out.println("Randomly put a ball to cup");
        int cupnumber = (int) ((Math.random()*6)+1);

        System.out.println("Guess where is it");
        int guess;
        guess = Input.nextInt();

        **while(cupnumber!=guess)
        {
            System.out.println("Guess a number");
                guess = Input.nextInt();
                guess(cupnumber,guess);
        }**
    }

    public static void guess(int cupnumber, int guess)
    {
            if(cupnumber == guess)
                System.out.print("Guess it correctly");
            else
                System.out.println("Try again");

    }

}

我是java编程新手。在上面的代码中,如果 while 循环部分下没有这些括号 {},如果 cupnumber 不等于猜测,我将无法重新输入数字。然而,通过 while 循环下的这些 {} 括号,如果 cupnumber 不等于猜测,我可以重新输入一个数字。

为什么括号会产生如此大的差异?

有人可以帮助我吗?谢谢

最佳答案

这是一个相当简单的解释。如果没有括号,它将重复第一行:

while(cupnumber!=guess)

    System.out.println("Guess a number");//Repeats this over and over
    guess = Input.nextInt();//These two are called outside the loop
    guess(cupnumber,guess);

但是像这样:

while(cupnumber!=guess)
{
    //Now all three lines are a part of the statement
    System.out.println("Guess a number");
    guess = Input.nextInt();
    guess(cupnumber,guess);
}

它表示执行括号内的所有操作。如果没有括号,则只会执行一行操作,但使用括号时,循环内的所有内容都会完成。

这个:

while(cupnumber!=guess)
    Single statement

是一种处理单行 if 语句(或 while)的简单方法。但是,需要括号才能使 Java“理解”if 语句或 while 语句在 true 语句上执行几行(如果 cupnumber !=guess 则该语句为 true)

while (condition) {
     Several statements
}

关于Java while循环括号函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38539635/

相关文章:

java - java中如何从数据库中获取json对象

c - 如何从 C 函数内部将变量扫描到数据结构中

javascript - 类列表.add()。如何插入变量而不是字符串?

python - 如何找到 while 循环执行了多少次?

PHP在while循环中添加+1

java - 基于 JBoss EJB 的 Web 服务日期格式

java - 取消部署 JBoss Drools 应用程序时出现异常

loops - 使用 Google Colabs 在循环内绘图

java - 查找数字的平均值(使用 while 循环;java)

java - 对 4GB JVM 和 3GB 缓存进行适当的 JVM/GC 调优