首页 > 解决方案 > 读取字符串时遇到问题

问题描述

Scanner s = new Scanner(System.in)  
int x = S.nextInt();  
double y = S.nextDouble();  
S.nextLine();  //Why 
String z = S.nextLine();  

为什么我需要S.nextLine()在读取 int & double 之后才能读取 String ?

标签: javajava.util.scanner

解决方案


如果您有以下信息

Line 1: 1.0 2.0 4.0(you are currently here after reading the double 4.0) \n
Line 2: (you are here once you eat that '\n' character using readLine())

一旦你存储了最后一个数字:4,你仍然在同一行(第 1 行)。你需要吃掉那个换行符。s.nextLine()将读取到行尾并返回空结果。完成后,扫描仪将位于第 2 行的开头。


推荐阅读