Java用户输入nextLine()不等待输入

时间:2015-10-16 08:02:55

标签: 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( "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??

任何解决此问题的方法,请帮忙?

1 个答案:

答案 0 :(得分:0)

我要做的一件事就是将id设置为字符串。我的意思是为了省去自己的头痛,除非你做的事需要你把它保存为实际整数然后我建议将Id移到最后。

import java.util.Scanner;

公共类LetsLearnJava {

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);

}

}