0

This is a continuation of a previous question to which i was unable to get an answer. The problem is when i try end the program using the System.exit(0) method with a switch statement and a "End" keyword and case, the code no longer runs as it should, only every second integer input is now read by the computer. Here is my method that is no longer working:

public static int[] ourGuess() {
    int[] guessed = new int[4];
    Scanner scan = new Scanner(System.in);
    System.out.println("Take your guess:");
    switch (scan.nextLine()) {
    case "End":
        System.exit(0);
        break;
    }
    guess = scan.nextInt();
    int mod = 10;
    int div = 1;
    for (int i = 3; i >= 0; i--) {
        int num = (guess % mod) / div;
        guessed[i] = num;
        div = div * 10;
        mod = mod * 10;
    }
    return guessed;
}

The class is a java implementation of the mastermind game. Thanks for all the help!

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

3 Answers3

1

You're reading two values from the Scanner.

First you read a value with scan.nextLine(), then you discard that value and read another with scan.nextInt().

You need to save the value read and reuse it:

final String line = scan.nextLine();
if(line.equals("End")) {
    return guessed;
}
final int guessed = Integer.parseInt(line);

You also shouldn't call System.exit.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
0

First of all, you should not use a switch statement for one case. Also, if the line read is not "End" but an int, you are skipping that one. Try:

String next = scan.nextLine();
if(next.equalsIgnoreCase("End")) System.exit(0);

Then check to see if next is the actual int that was guessed, otherwise read the next int.

Gregory Basior
  • 300
  • 1
  • 9
0

By calling nextLine() and nextInt(), you are reading two things from the stream. Instead, cache the value of the nextLine():

String line = scan.nextLine();
switch (line) { ...}

then use that in the following way:

guess = Integer.parseInt(line);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243