【问题标题】:How to fix my problem with 'nextLine()' in my input?如何解决我输入中的“nextLine()”问题?
【发布时间】:2020-01-01 20:21:46
【问题描述】:

我可以理解为什么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;

【问题讨论】:

    标签: java next


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多