首页 > 解决方案 > 如何使用扫描仪读取整数,更具体地说是描述矩阵维度的整数,然后是矩阵中的整数?

问题描述

我无法让我的扫描仪从文本文件中读取整数。

该文件看起来像这样(一个矩阵大小,后跟一个矩阵)

3
0 1 1 
1 1 1 
1 0 0  

这两种方法属于ReadMatrix

   public void openFile() {
      try {
         scanner = new Scanner(System.in); // create a scanner object
         System.out.println("File to read: ");

         fileName = scanner.nextLine(); // get name of file
         System.out.println("File " + fileName + " is opened.");
         br = new BufferedReader(new FileReader(fileName));
      } catch (Exception e) {
         System.out.println("can't find the funky file");
      }
   }

   public int readInteger() {
      sc = new Scanner(System.in);
      // while(sc.hasNextInt()){
      // sc.nextLine();
      anInt = sc.nextInt();
      System.out.println("Trying to read integerrrrrr help");
      // }
      return anInt;
}

这里有2个班


public class MainMethodHere {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      RunMainMethod running = new RunMainMethod(); 
   }
}


public class RunMainMethod {
   ReadMatrix a = new ReadMatrix(); 
  public  RunMainMethod(){
     a.openFile();
     a.createFile();
     System.out.println("just createdFile"); //<--- this is where the program ends
     a.readInteger();  
     System.out.println("just readInteger");
     a.helpMeWrite();
     System.out.println("Just write sample ");

     a.closeResources();
  }
}

写入文件工作正常,但我无法让程序读取给定的文本文件以开始操作。

我尝试在一些 SO 帖子中找到解决方案:如何从 Java 中的文本文件中读取整数 将 .txt 文件中的数字读取到二维数组中并在控制台上打印 如何从文本文件中读取整数值

我还尝试了 ReadFile() 和 WriteFile(),但是当我尝试通过打印到控制台来跟踪我的代码时,我的简单整数显示为不同的值。这与字节有关吗?所以我尝试恢复使用扫描仪,但不知何故它不起作用。如果我应该进一步澄清一些事情,请告诉我。我是编码和 SO 的新手。

标签: javafile-io

解决方案


推荐阅读