2014-03-27 109 views
1

我一直在嘗試自己學習Java大約一週,而且我決定嘗試將我的(相當有限的)知識應用於製作一個簡單的猜謎遊戲。學習Java - 製作一個簡單的猜謎遊戲

基本上,用戶輸入一個介於1到10之間的數字,並根據他們是否猜測得太高,太低或正確猜測隨機數字而得到反饋。

我的問題是,一旦我運行我的方法,我不知道如何允許多個猜測。基本上他們猜測一次,然後就是這樣。遊戲結束。

我敢肯定它就像我需要實現的循環一樣簡單,如果他們猜錯了,可能會聲明一個額外的變量?我不知道。

任何人都可以幫我嗎?

這裏是我的代碼:

import java.util.Scanner; 
import java.util.Random; 

public class GuessingGame { 
public static void main(String[] args) { 

    //creates a new scanner object 
    Scanner input = new Scanner(System.in); 

    // randomly generates a number from 1-10 
    Random rand = new Random(); 
    int myNumber = rand.nextInt(10)+1; 


    String tooWarm = "Too high. Try again!"; 
    String tooCold = "Too cold. Try again!"; 
    String bingo = "Yup! Good guess!"; 
    boolean playing = true; 

    System.out.printf("What's your name? "); 
    String name = input.nextLine();  
    System.out.println("Well, " + name + ", betcha can't guess what number I'm thinking of! \nHint: it's between 1 and 10..."); 
    int value = input.nextInt(); 


     if (value > myNumber) { 
      System.out.println(tooWarm); 
     } 

     else if (value < myNumber) { 
      System.out.println(tooCold); 
     } 

     else { 
      System.out.println(bingo); 
     }   

} 
} 
+1

你需要一個循環:'while(!input.equals(「stop」))' –

回答

1

只是這樣做,

do..while讓你執行,以ATLEAST執行一次。

do { 

     System.out.println("Enter : "); 
     int value = input.nextInt(); 

     if (value > myNumber) { 
      System.out.println(tooWarm); 
     } 

     else if (value < myNumber) { 
      System.out.println(tooCold); 
     } 

     else { 
      System.out.println(bingo); 
      playing = false; 
     } 
    } 
    while (playing); 
0

添加到您的代碼的末尾:

... 
char yN = input.nextChar(); 
if (yN == 'y' || yN == 'Y') { 
    main(null); 
    return; 
    } 
}//end of main(). 

基本上它的作用是,它使得遞歸調用,使遊戲可以一遍又一遍播放。 :-)

0
import java.util.Scanner; 
import java.util.Random; 

public class GuessingGame { 
    public static void main(String[] args) { 

    //creates a new scanner object 
    Scanner input = new Scanner(System.in); 

    // randomly generates a number from 1-10 
    Random rand = new Random(); 
    int myNumber = rand.nextInt(10)+1; 


    String tooWarm = "Too high. Try again!"; 
    String tooCold = "Too cold. Try again!"; 
    String bingo = "Yup! Good guess!"; 
    boolean playing = true; 

    System.out.printf("What's your name? "); 
    String name = input.nextLine();  
    System.out.println("Well, " + name + ", betcha can't guess what number I'm thinking of! \nHint: it's between 1 and 10..."); 
    while(true){ 
     int value = input.nextInt(); 


     if (value > myNumber) { 
      System.out.println(tooWarm); 
     } 

     else if (value < myNumber) { 
      System.out.println(tooCold); 
     } 

     else { 
      System.out.println(bingo); 
      return; 
     }   

    } 
}