使用扫描仪的Java将txt输入到二维数组

时间:2023-01-25 21:53:59
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class test{
   public static final int SIZE = 30;
   public static final int DUE_DATE = 15;
   public static final int TASK_NUMBER = 30;
   public static void main(String[] args)throws FileNotFoundException{
      Scanner console = new Scanner(System.in);
      System.out.println("Enter input file: ");
      String inputCompletionName = console.next();

      boolean[][] completion = new boolean[TASK_NUMBER][SIZE];
      File inputCompletion = new File(inputCompletionName);
      Scanner in = new Scanner(inputCompletion);
      int i = 0, j = 0;
      for(j = 0; j < SIZE; j++){
         for(i = 0; i < TASK_NUMBER; i++){
            while(in.hasNextBoolean()){         
               boolean input = in.nextBoolean();
               completion[i][j] = input;
            }
            System.out.println(completion[i][j]);
         }

      }
   }

I tried this code. My input is some boolean value but the output only have first element. Really don't know how to fix this.

我试过这段代码。我的输入是一些布尔值,但输出只有第一个元素。真的不知道如何解决这个问题。

My input file is just some random boolean values like this.

我的输入文件只是一些像这样的随机布尔值。

true false true false true

真假真真假

But the output only shows the first element.

但输出只显示第一个元素。

1 个解决方案

#1


1  

The problem is this:

问题是这样的:

while(in.hasNextBoolean()) { 
     boolean input = in.nextBoolean();
     completion[i][j] = input;
}

And that is inside your 2 for loops, so you read your booleans into the same grid cell.

这是在你的2 for循环中,所以你将你的布尔值读入同一个网格单元格。

This will work:

这将有效:

for(j = 0; j < SIZE && in.hasNextBoolean(); j++){
    for(i = 0; i < TASK_NUMBER && in.hasNextBoolean(); i++){      
        boolean input = in.nextBoolean();
        completion[i][j] = input;
        System.out.println(completion[i][j]);
    }
}

#1


1  

The problem is this:

问题是这样的:

while(in.hasNextBoolean()) { 
     boolean input = in.nextBoolean();
     completion[i][j] = input;
}

And that is inside your 2 for loops, so you read your booleans into the same grid cell.

这是在你的2 for循环中,所以你将你的布尔值读入同一个网格单元格。

This will work:

这将有效:

for(j = 0; j < SIZE && in.hasNextBoolean(); j++){
    for(i = 0; i < TASK_NUMBER && in.hasNextBoolean(); i++){      
        boolean input = in.nextBoolean();
        completion[i][j] = input;
        System.out.println(completion[i][j]);
    }
}