非常感谢大家的帮助,两个答案都很完美。我有一个 Java 实验室作业,我需要一些帮助。
任务是读取一个包含 28 个整数的 txt,然后将它们放入 2D 数组中。这是我所拥有的:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TextFileExample {
public static void main(String[] args) {
String fileName = "TemperatureData.txt";
Scanner inputStream = null;
System.out.println("The file " + fileName + "\ncontains the following lines:\n");
try
{
inputStream = new Scanner(new File("C:\\Users\\username\\Documents\\TemperatureData.txt"));//The txt file is being read correctly.
String line = inputStream.nextLine();
String[] numbers = line.split("");
int[][] temperatures = new int[4][7];
for (int row = 0; row < 4; row++) {
for (int column = 0; column < 7; column++) {
temperatures[row][column] = temperatures.parseInt(temperatures[row][column]);//Is this correct?
}
}
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
System.exit(0);
}
while (inputStream.hasNextLine())
{
String line = inputStream.nextLine();
System.out.println(line);
}
inputStream.close();
}
}
我需要一些关于将数据从 txt 文件中获取到数组中的帮助temperatures[4][7]
。
然后打印出显示数据的温度数组。输出应如下所示:
Temperature Data
Week 1: 73 71 68 69 75 77 78
Week 2: 76 73 72 72 75 79 76
Week 3: 79 82 84 84 81 78 78
Week 4: 75 72 68 69 65 63 65
他不要求将 txt 文件作为输出。
txt文件是这样的:
73
71
68
69
75
77
78
76
73
72
72
75
79
76
79
82
84
84
81
78
78
75
72
68
69
65
63
65