0

Im trying to put new Values into Arrays but for some reason at point where the scanner waits for my input the process terminates.

The relevant part:

Arrays:

public static String folders[] = { "Ordner 1", "Ordner 2", "Ordner 3", "Ordner 4", "Ordner 5" };
public static BigDecimal value[] = new BigDecimal[5];

And the void:

public static void session_start() {
    Scanner scanner = new Scanner(System.in);
    System.out.println("");
    System.out.println("Bitte gib einen Befehl ein: ");
    String eingabe = scanner.nextLine();
    switch (eingabe) {
    case "exit": {
        System.exit(1);
    }
    case "neuer Ordner": {
        BigDecimal new_value = new BigDecimal("0");
        System.out.println("Name des Ordners?");
        String name = scanner.nextLine();
        System.out.println("Der wievielte Ordner soll es sein (maximal 5)?");
        int order = scanner.nextInt();
        try {
            System.out.println("Möchtest du einen Betrag zuweisen?");
            String ja_nein = scanner.nextLine();
            if(ja_nein.equals("Ja") || ja_nein.equals("ja")) {
                System.out.println("Bitte gib den Betrag an: ");
                new_value = scanner.nextBigDecimal();
            }
        } catch (Exception f) {
            f.printStackTrace();
        }
        folders[order - 1] = name;
        value[order - 1] = new_value;
    }
    }
}

If i come to the line:

System.out.println("Möchtest du einen Betrag zuweisen?");
String ja_nein = scanner.nextLine();

The process terminates.

The try {} was just for testing purposes and my own search for the bug but i couldn´t find it.

KBS_Shabib
  • 41
  • 1
  • 9

1 Answers1

0

As @TiiJ7 said in the comments. You must be careful when collecting both ints and strings from the same Scanner because of the fact that nextInt() leaves the \n on the buffer, it will cause any nextLine's afterwards to instantly return empty. Most seasoned Java developers, actually use 2 Scanners one for numbers, and the other for strings.

For example:

Scanner stringInput = new Scanner(System.in);
Scanner numInput = new Scanner(System.in);
int valueToScan = numInput.nextInt();
String nextLine = stringInput.nextLine();

In your situation the line:int order = scanner.nextInt(); is leaving a \n character in the Scanner's internal buffer. Therefore, when nextLine gets called, it immedietly returns with an empty string, because it immedietly hits the remaining \n character.

Dylan
  • 1,245
  • 6
  • 19