2016-07-23 60 views
0

我的代碼:的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不等於猜測,我可以重新輸入一個數字。

爲什麼括號會產生這樣的差異?

任何人都可以幫助我嗎?謝謝

+0

括號決定循環內部的內容 - 每次重複的語句。沒有括號,只有第一個語句('System.out.println')。也就是說,「while(condition)something; somethingElse;'相當於'while(condition){something; } somethingElse;'。 – Ryan

回答

0

沒有括號,while語句的下一行被當作while循環和其他下面的語句不是循環的一部分。這裏的下一個陳述意味着具有分號的陳述。

當cupnumber不等於輸入數字時,爲什麼不能輸入另一個數字,是因爲while循環將繼續運行,直到提供的條件爲真。

無支架,這是你的while循環

while(cupnumber!=guess) 
System.out.println("Guess a number"); 
1

這是一個相當簡單的解釋。如果沒有括號,就會重複第一行:

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語句(或同時)。然而,需要支架使Java「理解」的if語句或while語句確實在真實的說明幾行(如果cupnumber!=猜則聲明是真實的)

while (condition) { 
    Several statements 
} 
0
guess = Input.nextInt(); will not be called if it's not inside the bracket. 

當您使用大括號,裏面有什麼是一個這將被視爲一個單獨的語句。所以下面的語句將會一個接一個地運行。

System.out.println("Guess a number"); 
guess = Input.nextInt(); 
guess(cupnumber,guess); 

如果沒有大括號,只有第一個語句可以在while條件定義後立即運行。

檢查Is there a difference in removing the curly braces from If statements in java瞭解更多詳情。謝謝。希望它會有所幫助。

0

發生這種情況是因爲範圍的您與{}

定義,如果你這樣做:

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

的Java是隻執行該語句System.out.println("Guess a number");如果條件得到滿足......

,所以你需要定義範圍是會重複的代碼 ....

同樣適用於 if-else,循環等...