gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:30:17 24 4
gpt4 key购买 nike

我能理解为什么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 () 将获取该行上 2 之后的所有内容,这将是什么都没有。

如果您将 nextnextIntnextLine 混合使用,则始终需要执行此操作。

关于java - 如何解决我的输入中的 'nextLine()' 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57695235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com