2017-10-10 79 views
0
import java.util.Random; 
import java.io.*; 
import java.util.*; 
/** 
    Courtney Fox 
    Professor Yao 
    Midterm Part 1 
    10/10/17 
    Purpose: 
     The purpose of this program is to develop a Nim game that consists of a 
     pile of stones ranging from 10-16. From that pile, both the player and 
     computer have to pick up to 3 stones and whoever gets the last stone 
     loses. 
    Logic: 
**/ 
public class FoxMidQ1 
{ 
    public static void main(String[] args) 
    { 
     //Variables 
     int user = 0; 
     //int computer; 
     //int loser; 
     int gamenum = 0; 
     //Scanner 
     Scanner input = new Scanner(System.in); 
    //Welcome Output 
    System.out.println("Welcome to Nim Game!"); 
    //Get pile size: Randomly generate 10-16 
    int[] pile = {10, 11, 12, 13, 14, 15 , 16}; 
    int stones = pile[(int)(Math.random() * pile.length)]; 
    System.out.println("Game #"+ (gamenum + 1) +": There are "+ stones + " 
    stones in the pile."); 
    System.out.println("You can remove up to 3 stones from pile at a 
    time."); 
    //User takes stones 
    System.out.println("How many stones would you like to remove? "); 
    user = input.nextInt(); 

我得到了初開始,但我被困在其中部分用戶只假設取1,2,或者從一堆石頭3。我嘗試過這樣做,而如果其他和這些循環都沒有做我想做的事情,因爲用戶只能假設有一個回合,那麼它的計算機就會從堆中取出3塊石頭。我如何限制用戶僅輸入1-3

+0

'如果(輸入> 3)'顯示一條消息,並要求再次輸入? –

+1

因爲任何數字都是你的測試失敗大於一或小於3 –

+0

的System.out.println(「你有多少石頭要刪除?」); user = input.nextInt(); 如果(用戶< 1 || user > 3) { 的System.out.println( 「請僅需要最多每圈3米的石頭。」); System.out.println(「你想移除多少塊石頭?」); user = input.nextInt(); } 別的 { INT stone1 =石頭 - 用戶; System.out.println(「There +」+ stone1 +「left left。」); } 我如何獲得它不斷向用戶詢問@LeonardoAlvesMachado – Courtney

回答

1

在這裏,你正在服用的來自用戶的輸入

System.out.println("How many stones would you like to remove? "); 
user = input.nextInt(); 

服用輸入後,就比較值的,如果是在1和3之間,然後提示正確的,如果不是在1和3之間,然後只顯示一條消息,說「輸入應該在1和3之間」。

if(user >0 && user <= 3) { 
    //do the needful 
} else { 
    //Print the custom message saying that wrong input 
} 
+0

如果用戶輸入超過2個錯誤數字,因爲它不迴環繞@Kamal Chanda – Courtney

+0

嘿,你可以嘗試像這樣加入 'boolean check = true; \t同時(檢查){ \t的System.out.println( 「你有多少石頭要刪除?」); \t user = input.nextInt(); \t \t if(user> 0 && user <= 3){ \t \t \t check = false; \t \t} else { \t \t \t System.out.println(「Invalid input please enter again」); \t \t \t校驗= TRUE; \t \t} \t \t \t} –

0

user = input.nextInt();

boolean testForCorrectInput = true; 
while(testForCorrectInput) 
{ 
     if(user < 1 || user >3) 
     { 
      System.out.println("\nWrong input. Please enter a number between 1 and 3"); 
      user = input.nextInt();  
     } 
     else 
      testForCorrectInput = false; 
} 

這增加,這將測試用戶是否已經輸入了正確的輸入,並促使他們進入,直到已輸入1和3之間的值。