[英]Why get i InputMismatchException when i use scanner sc.nextDouble()
I'd like to read data from a txt
file, but I get InputMismatchException
when I call nextDouble()
method. 我想从
txt
文件中读取数据,但是当我调用nextDouble()
方法时,我得到InputMismatchException
。 Even though I am using the useLocale
method, but it doesn't work. 即使我使用
useLocale
方法,但它不起作用。
The txt file first line is: 1;forname;1.9
txt文件的第一行是:
1;forname;1.9
public class SimpleFileReader {
public static void main(String[] args){
readFromFile();
}
public static void readFromFile(){
try {
int x = 0;
File file = new File("read.txt");
Scanner sc = new Scanner(file).useDelimiter(";|\\n");
sc.useLocale(Locale.FRENCH);
while (sc.hasNext()){
System.out.println(sc.nextInt()+" "+sc.next()+" "+sc.nextDouble());
x++;
}
System.out.println("lines: "+x);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Blame the French locale: it uses comma as a decimal separator, so 1.9
fails to parse. 归咎于法语区域设置:它使用逗号作为小数分隔符,因此
1.9
无法解析。
Replacing 1.9
with 1,9
fixes the problem ( demo 1 ). 用
1,9
替换1.9
修复了问题( 演示1 )。 If you would like to parse 1.9
, use Locale.US
instead of Locale.FRENCH
( demo 2 ). 如果要解析
1.9
,请使用Locale.US
而不是Locale.FRENCH
( 演示2 )。
A second problem in your code is the use of \\\\n
as the separator. 代码中的第二个问题是使用
\\\\n
作为分隔符。 You should use a single backslash, otherwise words that contain n
would break your parsing logic. 您应该使用单个反斜杠,否则包含
n
单词将破坏您的解析逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.