在这里,我可以在文件上写字。但是当我试图读取我的文件时,它给了我“MyFile.txt”但我的输出应该是“我 20 岁”我的代码有什么问题?
import java.util.*;
class main{
public static void main(String[] args){
Formatter fr;
try{
fr = new Formatter("MyFile.txt");
fr.format("I'm %d",20);
fr.close();
}catch (Exception e){
System.out.println("Error");
}
try {
Scanner sc = new Scanner("MyFile.txt");
while (sc.hasNext()){
System.out.println(sc.next());
}
sc.close();
}catch (Exception e){
System.out.println("Error");
}
}
}
Run Code Online (Sandbox Code Playgroud)
您正在将字符串文字传递给 Scanner 构造函数。
Scanner sc = new Scanner("MyFile.txt");
Run Code Online (Sandbox Code Playgroud)
那是扫描字符串本身的构造函数。
你想传递给它一个 File 对象:
Scanner sc = new Scanner(new File("MyFile.txt"));
Run Code Online (Sandbox Code Playgroud)
注意:使用 Formatter 写入文件的方式与您的工作方式相同,因为采用 String的Formatter构造函数假定该字符串是文件名。Scanner 构造函数假定字符串本身是输入,而不是文件名。
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |