Java |字符串类型
我遇到了一个我不明白的问题nextLine()应该用于句子,对吗Java |字符串类型,java,string,Java,String,我遇到了一个我不明白的问题nextLine()应该用于句子,对吗 System.out.println("Enter film's name"); a = scan.nextLine(); System.out.println("What number did the film released?"); b = scan.nextInt(); System.out.println("Who's the director?"); c = scan.nextLine(); System.out.pr
System.out.println("Enter film's name");
a = scan.nextLine();
System.out.println("What number did the film released?");
b = scan.nextInt();
System.out.println("Who's the director?");
c = scan.nextLine();
System.out.println("How long is the film in minutes?");
d = scan.nextInt();
System.out.println("Have you seen the movie? Yes/No?");
e = scan.next();
System.out.println("Mark for the film?");
f = scan.nextDouble();
它一直正确运行到发行日期,然后它一起显示“谁是导演”和“这部电影有多长时间”并且不像它应该工作的那样工作
如何使用nextLine()为什么它对我不起作用?缓冲区被填满了,每次连续呼叫后都会重置扫描仪。scan.reset()。原因是输入流中缓存了前面的字符。您的问题是
Scanner.nextInt()
无法读取到下一行。因此,您也需要发出nextLine(
)调用并丢弃它们的内容:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter film's name");
String a = scan.nextLine();
System.out.println("What number did the film released?");
int b = scan.nextInt();
scan.nextLine(); // this
System.out.println("Who's the director?");
String c = scan.nextLine();
System.out.println("How long is the film in minutes?");
int d = scan.nextInt();
scan.nextLine(); // this
System.out.println("Have you seen the movie? Yes/No?");
String e = scan.next();
System.out.println("Mark for the film?");
double f = scan.nextDouble();
scan.nextLine(); // after nextDouble() too
}
你能描述一下你的实际问题吗?类似的问题已经回答了。请参阅nextInt将下一个标记扫描为int值。因此,无论何时进行整数输入,都必须附加\n因此答案是:在nextInt调用之后添加一个
scan.nextLine()
,并且nextInt()不使用输入中的最后一个换行ascii字符。要记住这一点,请使用scan.nextLine()获取int值,然后使用Integer.parseInt(scan.nextLine())。但是,首先获取整数,检查它是否为整数,然后执行parseInt转换。不要使用nextInt()或next。这很有效,谢谢。解决了的!你介意接受这个答案吗?