-2

I am not sure why the loop doesn't work? I keep getting an error. It works the first time around but after that, it says that it's out of bounds? Please help, I'm confused.

public static void main(String[]args) {
Scanner user = new Scanner(System.in);
boolean yn = true;
char choice;

while (yn) {
System.out.println("Please enter your first name and last name, separated by a space.");
    String name=user.nextLine();
        name = name.trim();
        int r = name.indexOf(" ");
        String first = name.substring(0,r);
        String last = name.substring(r+1);
        int lengthlast = last.length();
System.out.println("Hello there " + first + " I have your first name as " +  first + ", which has " + r + " characters.");
System.out.println("Hello again " + first + " I have your last name as " + last + ", which has " + lengthlast + " characters.");
    String firstinit = name.substring(0,1);
        firstinit = firstinit.toUpperCase();
    String lastinit = name.substring(r+1,r+2);
        lastinit = lastinit.toUpperCase();
System.out.println("Did you know that your initials are " + firstinit + "" + lastinit);
System.out.println("Do you wish to continue? (Y)yes or (N)no ?");
    choice = user.next().charAt(0);
        switch (choice) {
            case 'y':
                yn=true;
                break;
            case 'Y':
                yn=true;
                break;
            case 'n':
                yn=false;
                break;
            case 'N':
                yn=false;
    }

}

}

1 Answers1

-1

Don't mix nextLine and next. In fact, don't use nextLine. If you want to read everything until the user presses enter, tell the scanner that you consider the newline the 'delimiter' and not any whitespace, so, after making your scanner: scanner.useDelimiter("\r?\n"); - and now you can use .next(), which will give you the next line, reliably, without having to mess with 'consuming the newline'.

EDIT: Added the requisite question mark.

rzwitserloot
  • 44,252
  • 4
  • 27
  • 37
  • I didn't downvote you but, that's the good thing about Scanner#nextLine(), there is **no** `having to mess with 'consuming the newline'`, it does it for you. – DevilsHnd Apr 20 '20 at 05:49
  • Why is `useDelimiter("\r\n")` + `next()` better than only using `nextLine()`? For one, it's surely not better, because it would fail on Linux. – Andreas Apr 20 '20 at 05:50
  • I typoed; there's supposed to be a question mark in there. Using readLine() to 'eat up the newline' means your app fails when the user decides to enter, say, 2 numbers separated by a space instead of a newline. Note, _ONLY_ using nextLine() is perfectly fine, it's mixing where it goes wrong. Then it's better than use next + nextInt() and co, updating the delimiter if you want entire lines instead of single words. – rzwitserloot Apr 20 '20 at 09:36