我的代碼:的Java while循環包圍功能
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不等於猜測,我可以重新輸入一個數字。
爲什麼括號會產生這樣的差異?
任何人都可以幫助我嗎?謝謝
括號決定循環內部的內容 - 每次重複的語句。沒有括號,只有第一個語句('System.out.println')。也就是說,「while(condition)something; somethingElse;'相當於'while(condition){something; } somethingElse;'。 – Ryan