我不知道代码有什么问题,而且我什至不知道归档的基础知识。请任何人帮忙。 它接受标记和注册编号甚至标记的输入,但不显示标记 我该怎么办?
class Info
{
public void writeFile() throws IOException{
try{
FileWriter f = new FileWriter("D:\\Student.txt");
Scanner in=new Scanner(System.in);
PrintWriter fw = new PrintWriter(f) ;
System.out.println("Enter Student's Name");
String name=in.nextLine();
System.out.println("Enter Student's Reg.No");
String reg_no=in.nextLine();
Scanner inp=new Scanner(System.in);
System.out.println("Enter Student's marks");
int marks=inp.nextInt();
fw.write(name);
fw.write(reg_no);
fw.write(marks) ;
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public void readFile() throws IOException
{
try{
FileReader reader =new FileReader("D:\\Student.txt");
Scanner in=new Scanner(reader);
while(in.hasNext())
System.out.println(in.next());
reader.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
最佳答案
此行之后 fw.write(marks);
的问题 intmarks=inp.nextInt();
你传递的marks
这是 int
到 write(int c)
,它位于 PrintWriter
类
/**
* Writes a single character.
* @param c int specifying a character to be written.
*/
public void write(int c) {
try {
synchronized (lock) {
ensureOpen();
out.write(c);
}
}
...
...
}
负责将您的int
写入单个字符
而不是int值,如果我们更深入,它会调用write(int c)
在 StreamEncoder
类中,如果您看到此方法的源代码
public void write(int c) throws IOException {
char cbuf[] = new char[1];
cbuf[0] = (char) c;
write(cbuf, 0, 1);
}
它正在获取您的 int
值并将其转换为 char
并存储到 char
中,这意味着它正在存储等效的 char
int
的值
如果您想要预期的输出,请更改您的代码
int 标记=inp.nextInt();
--> 字符串标记=inp.nextLine();
关于java - 为什么此代码不起作用?-通过扫描仪和 PrintWriter 归档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37378683/