2017-09-22 53 views
0

我已經做了一個街頭擲骰子游戲,並在開始時有一個錯誤檢查器,以確保輸入有效,我把它放在if語句中,然後將剩餘的代碼(用於有效輸入)作爲else,但是當用戶輸入有效數字時,它不會識別其他部分。如何讓方法識別else語句的一部分?

public void play() { //method 
    System.out.println("Please pick a number."); 
    guess = scan.nextInt(); 
    if (guess == 7 || guess == 1 || guess == 0 || guess > 12) { 
     System.out.println("Sorry, that is an invalid input, please choose another number."); 
     guess = scan.nextInt(); 
    } else { 
     int roll = dieOne.roll(); 
     int roll2 = dieTwo.roll(); 
     int rollSums = roll + roll2; 
     System.out.println(roll + "+" + roll2); 
     while (rollSums != 7) { 
      if (guess == rollSums) { 
       System.out.println("Congratulations, you win! Your number was rolled before a seven was rolled!"); 
       rollSums = 7; 
       guess = 7; 
      } else { 
       roll = dieOne.roll(); 
       roll2 = dieTwo.roll(); 
       rollSums = roll + roll2; 
       System.out.println(roll + "+" + roll2); 
      } 
     } 
     if (rollSums != guess) { 
      System.out.println("Sorry, your number was not rolled before a seven was rolled."); 
     } 
    } 
} 

回答

0

我想你想執行if部分,直到if條件不滿足,然後你想執行else部分。如果這是你想要的,你需要執行if部分作爲while循環,而else部分作爲while循環之後的代碼。

0

你需要一個while循環,以確保你得到一個良好的輸入,然後再做遊戲邏輯,像這樣:

int guess = scan.nextInt(); 
    while (guess == 7 || guess == 1 || guess == 0 || guess > 12){ 
     System.out.println("Sorry, that is an invalid input, please choose another number."); 
     guess = scan.nextInt(); 
    } 

    //Game Logic (Stuff in else section)