Search code examples
javawhile-loopswitch-statementblank-line

(Java) Exiting While Loop In Switch Case With Empty Line


To briefly explain, I'm supposed to get the user to enter the name of the recipient of a message, and then get them to enter the message body, which can have multiple lines. If they enter a blank line, then the message body ends and they can select another case in the switch.

case 'S':
case 's':
    if(user.equals(" ")) {
        System.out.println("No user logged in.");
    } else {
        System.out.println("Recipient: ");
        recip = menuScan.next();

        m = new Message(user,recip);

        System.out.println("Enter message. Blank line to quit.");
        mbody = menuScan.nextLine();

        while(!mbody.equals("")) {
            mbody = menuScan.next();
            m.append(mbody);
        }

        ms.deliver(m);

        System.out.println("Messgae sent.");

    }
    break;

But as it is now, the while loop is skipped completely. I've tried changing recip to menuScan.nextLine(), and mbody to menuScan.next() and .nextLine(), but the only other thing that happens is the message body goes on forever.

I've also tried using two different Scanner objects for recip and mbody, but no luck there, either.


Solution

  • I've tried this piece of your code

          System.out.println("Enter message. Blank line to quit.");
          mbody = menuScan.nextLine();
    
          while (!mbody.equals("")) {
               mbody = menuScan.next();
               m.append(mbody);
          }
    

    changing it a bit

          System.out.println("Enter message. Blank line to quit.");
          mbody = menuScan.nextLine();
    
          while (!mbody.equals("")) {
               m.append(mbody);
               mbody = menuScan.nextLine();          
          }
    

    This way the loop is executed and exited as expected. I have used java.util.Scanner