简体   繁体   中英

How do I make my do while loop with user prompt work?

I'm creating an application that basically works as a guessing game. At the end of the game I want to ask the user if they want to play again. If they type "Y" or "y", the game will restart, if any other character is entered, then the loop ends.

public class NumberGame {
public static void main(String[] args) throws java.io.IOException {
    int NumberGame;
    int NumberUser;
    char BonusResponse;
    char charGen;
    String Guess = " ";
    String Bonus = " ";

    do {
    NumberGame = (int) (Math.random() * 10);
    charGen = (char)(NumberGame + 48);
        //for(NumberGame < 1; NumberGame++){

            System.out.print("The computer generated number was " + NumberGame);
            System.out.print("\nGuess a number between 1 and 9: ");
            NumberUser = (char) System.in.read();
            NumberUser = (int) (NumberUser - 48);

    if (NumberGame > NumberUser)
        Guess = " Too low! Try again";
    else if (NumberGame == NumberUser)
        Guess = " Congratulations, you win!";
    else if (NumberGame < NumberUser)
        Guess = " Too high! Try again";

    System.out.println("You guessed " + NumberUser + "." + Guess);

    if (NumberGame == NumberUser)
        Bonus = "Now that you've won, wanna play again? Type Y to play again or any other key to exit:";
    else 
        Bonus = " ";

    System.out.println(Bonus);    

        BonusResponse = (char) System.in.read();

    } while (BonusResponse == 'Y' || BonusResponse == 'y');   
  }
}

You could use the Scanner Class instead of plain System.in.read()

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
String response= sc.next();

You can use Scanner class as seen on this answer or BufferedReader as seen on this answer .

Example with BufferedReader class:

import java.io.BufferedReader;
import java.io.InputStreamReader; 
class Areas {
    public static void main(String args[]){
        float PI = 3.1416f;
        int r=0;
        String rad; //We're going to read all user's text into a String and we try to convert it later
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Here you declare your BufferedReader object and instance it.
        System.out.println("Radius?");
        try{
            rad = br.readLine(); //We read from user's input
            r = Integer.parseInt(rad); //We validate if "rad" is an integer (if so we skip catch call and continue on the next line, otherwise, we go to it (catch call))
            System.out.println("Circle area is: " + PI*r*r + " Perimeter: " +PI*2*r); //If all was right, we print this
        }
        catch(Exception e){
            System.out.println("Write an integer number"); //This is what user will see if he/she write other thing that is not an integer
            Areas a = new Areas(); //We call this class again, so user can try it again
           //You can also print exception in case you want to see it as follows:
           // e.printStackTrace();
        }
    }
}

Example with Scanner class:

import java.util.Scanner;

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

        Scanner scan= new Scanner(System.in);

        //For string

        String text= scan.nextLine();

        System.out.println(text);

        //for int

        int num= scan.nextInt();

        System.out.println(num);
    }
}

You can try adding the reading code inside a do-while loop to validate user input. Then add this code after your while (BonusResponse == 'Y' || BonusResponse == 'y');

if (BonusResponse == 'y' || BonusResponse == 'Y') {
    startApplication();
}

move all your main() code to startApplication() method. And change main to:

public static void main(String args[]) {
    startApplication();
}

Also please follow Java naming conventions :

Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter . Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM