2015-10-16 40 views
0

我有这样的小问题,我输入:Java用户输入nextLine()犯规等待输入

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?? 

有什么办法解决这个问题,请帮忙?

+0

这是一个相当普遍的问题 - 基本上'nextInt()'不立即食用换行符号之后,所以你需要立即调用'.nextLine()'来摆脱它。 – JonK

回答

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

} 

}

+0

是的,这将是很好的看我猜,但我的指示说,ID必须是int,所以我不能这样做..谢谢反正! – DisasterCoder