-1

I'm having difficulties trying to get multiple inputs inside a do-while loop, inside a try/catch statement:

FileOutputStream file;
PrintStream pen;
String name;
char exitInput;

try {
        file = new FileOutputStream("names.txt");
        pen = new PrintStream(file);
        
        do {

            System.out.print("Enter a name: ");
            name = input.nextLine();
            
            pen.print(name + "\n");
            
            System.out.println("Would you like to enter more names?");
            System.out.print("Option(y/n): ");
            exitInput = input.next().charAt(0);
        
        } while(exitInput != 'n');
        
        pen.close();
    
    } catch(IOException exc) {
        
        System.out.println("<INPUT ERROR>");
    
    }

When I run this code, it ask me for a name, then ask me if I want to enter more names. If I choose YES, then it just skips the "name = input.nextLine();" line and display:

Enter a name: Would you like to enter more names?
Option(y/n):

Issue appears to solve when typing two "name = input.nextLine();", however, that's not a great solution.

Sereseli97
  • 11
  • 4
  • `while(exitInput != 'n')` Strings can't be compared like this. https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – markspace Oct 03 '20 at 05:53
  • Thank you, but "exitInput" is a char variable. Also, that's not the issue I'm trying to fix. – Sereseli97 Oct 03 '20 at 06:04

1 Answers1

0

input.next() consume only one token, not entire line. when you call input.nextLine() it consume rest of that line.

To fix that replace input.next() with input.nextLine().

talex
  • 15,633
  • 2
  • 24
  • 56