java - 为什么此代码不起作用?-通过扫描仪和 PrintWriter 归档

标签 java

我不知道代码有什么问题,而且我什至不知道归档的基础知识。请任何人帮忙。 它接受标记和注册编号甚至标记的输入,但不显示标记 我该怎么办?

       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这是 intwrite(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/

相关文章:

java - 读取 java 中的二进制文件直到特定的 "%%EOF"标记?

java - Eclipse Java控制台: Why sometimes no output?

java - 如何防止 "Firestore, Provided document path must not be null"错误?

java - 什么时候在android项目中回收位图?

java - 获取字符串中接下来的两个单词

java - 如何在java中打印0,1,2的字典排列

java - 需要类似 getTotal(ClassName, ListOfObjectsOfClass, numericFieldOfClass)

java - Java 如何检查一个值是否存在于数组中?

google-chrome - Java Selenium findelement 未确认页面上的元素

java - 使用 oscP5 处理 grasshopper