[英]Program unable to read from file and save to variable
当我运行我的代码时,它说有一个InputMismatchException? 适用于前两个读取行,但是我尝试读取int和双行,但不会读取,并且字符串行实际上未将任何内容读入变量,它为空,因为它不打印任何内容在system.out.println(a + b)...有什么提示吗?
import java.util.*;
import java.io.*;
class Uke55{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
try{
PrintWriter utfil=new PrintWriter(new File("minfil55.txt"));
utfil.println('A');
utfil.println("Canis familiaris betyr hund");
utfil.println(15);
utfil.printf("%.2f", 3.1415);
utfil.close();
}catch(Exception e){
e.printStackTrace();
}
try{
Scanner innfil=new Scanner(new File("minfil55.txt"));
char a=innfil.next().charAt(0);
String b=innfil.nextLine();
System.out.println(a +b);
int c=(int)innfil.nextInt();
double d=(double)innfil.nextDouble();
innfil.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
这是因为当您使用next(),nextInt()和nextDouble()时,它不会移至新行。 只有newLine()将光标移动到下一行。 做这个:
try{
Scanner innfil=new Scanner(new File("minfil55.txt"));
char a=innfil.nextLine().charAt(0); //first error was here. calling next() only
//read A and not the \r\n at the end of the
//line. Therefore, the line after this one was
//only reading a newline character and the
//nextInt() was trying to read the "Canis" line.
String b=innfil.nextLine();
System.out.println(a +b);
int c=(int)innfil.nextInt();
innfil.nextLine(); //call next line here to move to the next line.
double d=(double)innfil.nextDouble();
innfil.close();
}
catch(Exception e){
e.printStackTrace();
}
next(),nextInt(),nextDouble(),nextLong()等...都在任何空格(包括行尾)之前停止。
那是因为您有文件:
A\n
Canis familiaris betyr hund\n
15\n
3.14
其中\\n
代表换行符。
第一次打电话时
innfil.nextLine().charAt(0)
它读取A
,而扫描仪读取点指向第一个\\n
然后你打电话
innfil.nextLine()
它读取直到\\n
( nextLine()
读取直到\\n
并将扫描器读取指针放在\\n
),并使读取指针超过\\n
。 读指针将在下一行的C
。
然后你打电话
innfil.nextInt()
h! 扫描仪无法识别Canis
为整数,输入不匹配!
根据Scanner.nextLine()上的文档
“ 将此扫描程序前进到当前行之外,并返回被跳过的输入。 ”
因此,在调用char a=innfil.next().charAt(0);
“光标”在第一行的末尾。 调用String b=innfil.nextLine();
读取直到当前行的末尾(没有要读取的所有内容),并前进到下一行(实际的String所在的位置)。
解
在调用String b=innfil.nextLine();
之前,需要前进到下一行String b=innfil.nextLine();
:
...
char a=innfil.next().charAt(0);
innfil.nextLine();
String b=innfil.nextLine();
...
注意事项 :
虽然Scanner.nextInt()和Scanner.nextDouble()的行为方式相同Scanner.next() ,你不面对同样的问题,因为这些方法将读取下一个完整标记(其中“ 一个完整标记的前后其后跟匹配定界符模式 “) 的输入和空白字符(例如换行符)都被视为定界符。 因此,如果需要,这些方法将自动前进到下一行,以查找下一个完整的令牌 。
您是否检查过实际写入文件的内容? 我不信。 在关闭PrintWriter之前,请尝试调用flush()。 编辑:对不起,我在这里错了,因为我在考虑自动行刷新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.