1

I'm new to Java so forgive me. I'm writing a small little Guessing Game program.

import java.util.Scanner;

public class GuessingGame {

static Scanner userInput = new Scanner(System.in);

public static void main(String[] args) {
    int menuOption; 
    // Main Screen //
    System.out.println("Guessing Game");
    System.out.println("---------------------");
    System.out.println("1.) Play Game");
    System.out.println("2). Exit");
    System.out.println();           

    while (true) {
        System.out.print("Please select a menu option: ");                  
        menuOption = userInput.nextInt();

        if (menuOption == 2) {
            System.out.println("Exiting the game. Thanks for playing!");
            break; 

        } else if (menuOption == 1) {
            System.out.println("Let's start the game!");

            getRandomRange();

        } else {
                System.out.println("Sorry, that's not a valid option. Please try again.");
                continue;
        }
    }

}
/**
 * Determine the range of numbers to work with
 */
public static void getRandomRange() {
    int min;
    int max;

    System.out.print("Choose a minimum number: ");
    min = userInput.nextInt();

    System.out.print("Choose a maximum value: ");
    max = userInput.nextInt();

    getRandomNumber(min, max);
}

public static void getRandomNumber(int min, int max) {
    int randomNumber = (int) (Math.random() * (max - min + 1)) + min;

    getAGuess(min, max, randomNumber);
}

public static void getAGuess(int min, int max, int randomNumber) {
    int guess; 

    while (true) {
        System.out.print("Guess a number between " + min + " and " + (max) + ": ");
        guess = userInput.nextInt();

        if (guess == randomNumber) {
            System.out.println("Correct! The random number is: " + randomNumber);
            break;
        }
    }   
  }
}

When I prompt the user to guess a number and the number is incorrect, I want to be able to flush immediately flush the input stream and enter another guess on the same line.

For example: Guess a number between 0 and 5: I enter my guesses here on this one line only.

I could take the print out of the loop but in that case, if I enter an inccorect number, the cursor jumps to the next line.

Hope this makes sense. Thanks!

jmin91
  • 13
  • 1
  • 6
  • 1
    I don't think that's possible without modding the console but if it is possible I am pretty sure the solution is not cross platform. – GenuinePlaceholder Jan 18 '15 at 15:35
  • I'm not sure I understand what you are trying to achieve. Could you add an example of what you would want the output to look like? Would it be: Guess a number between 2 and 8: 2 3 4 5 Correct! The random number is: 5 – mmdeas Jan 18 '15 at 15:46
  • possible duplicate of [clear screen option in java](http://stackoverflow.com/questions/1682212/clear-screen-option-in-java) – SMA Jan 18 '15 at 15:51
  • @mmdeas Yes like that. Guess a number between 2 and 8: [guesses here] So the first guess is 2. It's incorrect and gets cleared so where I previously entered 2, that's gone and I can enter 3....etc until the answer is correct. All on that same line. – jmin91 Jan 18 '15 at 16:07
  • I see. I agree with @Coldawdawdawdawd that there's no nice way of doing this. You can't get the input until the user presses return (afaik) and can't delete past the newline. Clearing the screen (with an external command or lots of new lines) and reprinting the prompt is a workaround though. EDIT: As I've just seen Joe's answer suggest. – mmdeas Jan 18 '15 at 16:25
  • Yeah that's what I was thinking myself. I figured if there was a way, it would be well known and something I would've come across by now in learning Java. Thanks though! – jmin91 Jan 18 '15 at 16:55

2 Answers2

1

If your goal is only to clear the console, then you could do:

Runtime.getRuntime().exec("cls");

Or if you are on Linux or OS X:

Runtime.getRuntime().exec("clear");

Now if you add previous line that you wanted to keep, you will need to keep then in an Array and reprint after each clear.

This won't work in IDE's.


If you want a more system-independent way, there is a library named JLine (GitHub), which is designed for a better console usage. It actually contains a method clearScreen.


You could also do:

System.out.print("\033[H\033[2J");

This will clear the screen and return the cursor to the first row.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • Its a duplicate of [this](http://stackoverflow.com/questions/1682212/clear-screen-option-in-java) – SMA Jan 18 '15 at 15:52
  • haha glad you learned something! I just tried: Runtime.getRuntime().exec("cls"); but got an IO Exception error. Is there more to it than that one line of code? Thanks everyone btw. – jmin91 Jan 18 '15 at 16:11
  • What is the exception ? And what is your OS ? – Jean-François Savard Jan 18 '15 at 16:13
  • Windows 7. Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type IOException at GuessingGame.getAGuess(GuessingGame.java:73) at GuessingGame.getRandomNumber(GuessingGame.java:63) at GuessingGame.getRandomRange(GuessingGame.java:57) at GuessingGame.main(GuessingGame.java:37) I just caught the exception but it still moves the nextInt() cursor to the next line. – jmin91 Jan 18 '15 at 16:20
  • @jmin91 Can you post more of your code so I could debug myself ? It's hard to say what is happening at GuessingGame without having the code. – Jean-François Savard Jan 19 '15 at 14:19
  • @jmin91 You could try to output `System.out.print("\033[H\033[2J");` it may works on your console. This kind of job is really System dependent. Note that it won't work on any IDE. – Jean-François Savard Jan 20 '15 at 00:09
  • @Jean-FrançoisSavard I just posted the entire code above. I tried that print method in the Windows command line and here's what I got. Guess a number between 1 and 5: 2 ←[H←[2JGuess a number between 1 and 5: 3 ←[H←[2JGuess a number between 1 and 5: 2 ←[H←[2JGuess a number between 1 and 5: 3 ←[H←[2JGuess a number between 1 and 5: 4 ←[H←[2JGuess a number between 1 and 5: 2 ←[H←[2JGuess a number between 1 and 5: 1 Correct! The random number is: 1 Didn't really work. I really appreciate your help though. – jmin91 Jan 20 '15 at 03:25
0

A quick and dirty solution...

public class Main {


    public static final void main(String[] data) {

        Scanner userInput = new Scanner(System.in);
        int min = 0;
        int max = 10;
        int randomNumber = (int) ((Math.random() * max) + (min + 1));

        while (true) {
            System.out.print("Guess a number between " + min + " and " + max + ": ");
            int guess = userInput.nextInt();
            if (guess == randomNumber) {
                System.out.println("Correct! The random number is: " + randomNumber);
                break;
            } else {
                for (int i = 0 ; i < 25; i++) {
                    System.out.println();
                }
            }
        } 
    }
}
Joe
  • 86
  • 3
  • Thanks Joe - that clears the screen but I'm looking to keep that "Guess a number between. ... " output on the screen but just clear that line input. Appreciate it. – jmin91 Jan 18 '15 at 18:30