我能理解為什么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;
1 回答
桃花長相依
TA貢獻1860條經驗 獲得超8個贊
scan.nextLine()您需要在調用后添加一個調用scan.nextInt();,而不是使用其中的值:
int b=scan.nextInt(); scan.nextLine(); //Add this line
這是因為nextInt()不會消耗用于nextLine()確定行結束的行終止符,并且額外的調用nextLine()將正確地為您消耗它。
基本上,在你給它賦值之前2,例如,nextInt()將采用2,然后nextLine()將采用2THAT 行之后的所有內容,這將是什么。
next如果您將ornextInt與混合使用,則始終需要執行此操作nextLine。
添加回答
舉報
0/150
提交
取消
