【问题标题】:What is wrong with my program for Text I/O - Java我的文本 I/O 程序有什么问题 - Java
【发布时间】:2014-07-28 23:35:19
【问题描述】:

我一直在尝试制作一个程序,它可以读取 ASCII 十进制值的文本文件,将其转换为字符串并将它们打印到不同的文本文件中。

这是我所拥有的:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.io.PrintWriter;


public class ReadData {
 Scanner inFile;
 PrintWriter outFile;
  int number;

 public static void main(String[] args) {
    ReadData rd = new ReadData();
    rd.Run2();
    rd.Run3();
   }

 public void Run2() {
  String fileName = "ASCII.txt"; // text file that has the decimal values
  try {
   inFile = new Scanner(new File(fileName));
  } catch (FileNotFoundException e) {
   System.err.printf("ERROR: Cannot open %s\n", fileName);
   System.exit(1);
  }
  while (inFile.hasNext()) {
   number = inFile.nextInt();
   System.out.print(number + "   ");
  }

 }

 public void Run3() {
   try {
    outFile = new PrintWriter(new File("output.txt")); // the name of text file that should have the translated ASCII values
  } catch (IOException e) {
    e.printStackTrace();
    System.exit(1);
  }
number = inFile.nextInt(); // the decimal values in ASCII.txt
 char ch = (char)(number); // translating the values to corresponding char values
      outFile.print(ch);
     inFile.close();
  outFile.close();
 }

}

它编译成功并打印出十进制值,但是在打印十进制值并且 output.txt 文件为空白后出现错误...我做错了什么?谢谢。

【问题讨论】:

  • 如果你有十进制值,你为什么使用nextInt()
  • 将您的整个错误/异常和堆栈跟踪发布到您的问题中。

标签: java text io


【解决方案1】:

您必须重新初始化扫描仪。您在 Run2() 中将 Scanner 运行到文件末尾。在 Run3() 中,扫描仪已经位于文件末尾并引发异常。您所要做的就是删除 Run2() 中的 while 循环,就可以了。

ps:Java 标准建议方法不要大写。

【讨论】:

  • 我照你说的做了,只是把while循环放到了Run3()中,就成功了!谢谢!
  • @Qoy 如果对您有用,请将答案标记为正确,谢谢。
猜你喜欢
  • 1970-01-01
  • 2010-10-14
  • 2017-02-27
  • 2010-11-12
  • 1970-01-01
  • 2015-01-17
  • 1970-01-01
  • 2013-05-03
  • 1970-01-01
相关资源
最近更新 更多