如何解决输入中 'nextLine()' 的问题?

How to fix my problem with 'nextLine()' in my input?

我能理解为什么 nextLine() 不起作用。

如果我将 nextLine() 更改为 next(),我的输入不会包含所有短语

 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;

您需要在调用 scan.nextInt(); 之后添加对 scan.nextLine() 的调用并且不使用其中的值:

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

这是因为 nextInt() 不使用 nextLine() 中使用的行终止符来确定行的结尾,而对 nextLine() 的额外调用将​​为您使用它正确。

基本上在你给它赋值 2 之前,例如,nextInt() 将采用 2,然后 nextLine() 将采用 [=16] 之后的所有内容=] 在该行,这将是什么。

如果您将 nextnextIntnextLine 混合使用,则始终需要这样做。