1

I can understand why nextLine() doesnt work.

If I change nextLine() with next() my input doest take all the phrase

 case 7:
        System.out.println("Press 1 to post on your wall \nPress 2 to post on a friend's wall");
        int b=scan.nextInt();
        if(b==1){
            System.out.println("What do you want to post?");
            String pm=scan.nextLine();

            Message ms= new Message(loginUser.getUsername(),loginUser.getUsername() +" :"+ pm.toString());
            message.add(ms);
        }
        if(b==2){
            System.out.println("Whose wall do you want to post? (Write his/her username)");
            String ph=scan.next();

            for(int n = 0;  n< users.size(); n++)
            {
                if(!loginUser.getUsername().equals(ph) 
                        && users.get(n).getUsername().equals(ph)){
                    System.out.println("What do you want to post?");
                    String postIt=scan.nextLine();
                    Message me= new Message( ph,ph +" : "+loginUser.getUsername() +" : " + postIt.toString() );
                    message.add(me);
                }
            }
        } 
        luna=false;
        break;
Jonas
  • 121,568
  • 97
  • 310
  • 388
arxxx
  • 15
  • 3

1 Answers1

1

You need to add a call to scan.nextLine() after you call scan.nextInt(); and not use the value from it:

int b=scan.nextInt();
scan.nextLine(); //Add this line

This is because nextInt() does not consume the line terminator that is used in nextLine() to determine the end of the line and the extra call to nextLine() will consume it for you correctly.

Basically before you were giving it the value 2 for example, the nextInt() will take the 2, then nextLine() will take everything after the 2 on THAT line, which would be nothing.

This will always need to be done if you are mixing the use of next or nextInt with nextLine.

Nexevis
  • 4,647
  • 3
  • 13
  • 22