Java用户输入nextLine()不等待输入
我的输入有一个小问题:Java用户输入nextLine()不等待输入,java,Java,我的输入有一个小问题: public void input() { Scanner scn = new Scanner( System.in ); System.out.print( "Please enter id: " ); id = scn.nextInt(); System.out.print( "Please enter name: " ); title = scn.nextLine(); System.out.print( "Plea
public void input()
{
Scanner scn = new Scanner( System.in );
System.out.print( "Please enter id: " );
id = scn.nextInt();
System.out.print( "Please enter name: " );
title = scn.nextLine();
System.out.print( "Please enter author: " );
author = scn.nextLine();
}
现在我使用的是scn.nextLine()
,因为我想在命名和作者时使用空格,比如:
USER INPUT:
Story of Something
Sir Whatever
问题是,当我使用nextLine()
时,程序不会等待我的输入,它只是继续,我的控制台将如下所示:
Please enter id: 4632
Please enter name: Please enter author: what, why??
有没有办法解决这个问题,请帮助?我要做的一件事是将id设置为字符串。我的意思是省去你自己的头疼,除非你正在做一些事情,要求你把它保存为一个实际的整数,然后我建议把Id移到最后
import java.util.Scanner;
公共类LetsLearnJava
{
}这是一个非常常见的问题-基本上,
nextLine()
不会立即使用数字后面的换行符,因此需要在数字后面立即调用.nextLine()
,以消除它。是的,我想这看起来不错,但我的说明说id必须是int,所以我不能那样做。。无论如何谢谢你!
public static void main(String[] args) {
// TODO Auto-generated method stub
String title, author, id;
Scanner myScan = new Scanner( System.in );
System.out.print( "Please enter id: " );
id = myScan.nextLine();
System.out.print( "Please enter name: " );
title = myScan.nextLine();
System.out.print( "Please enter author: " );
author = myScan.nextLine();
System.out.print("You entered: " + id + " " + title + " " + author);
}