几天来我一直在努力解决这个问题,我觉得我只是被困在了一些很容易因为过度思考而变得很容易的事情上。我需要阅读文件,(文本文件的内容如下所示)...从每列中创建 3 个数组。
我的问题是在将“”条件下的字符串拆分为字符串 [] 数组时,获取我的 txt 的最后一行并将其放入新的字符串 [] 数组中,而不是我从文件中生成的字符串的全部内容...
我的 txt 文件看起来像这样......
200 1000 800
450 845 1200
800 250 400
0 1500 1800
600 500 1000
700 1400 1700
675 400 900
我的代码经过几天的操作、删除、从头开始……所有这些都是为了这个小片段。 请帮我!!!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class WeeklyCalorieCount {
public static void main(String[] args) {
try {
File input = new File("Lab1File.txt"); //reads file and names it input to refer back later
Scanner klg = new Scanner(input); //creates scanner that reads the file named input
String [] b = new String [7]; //creating breakfast, lunch and dinner Strings (To Split later)
String [] l = new String [7];
String [] d = new String [7];
String fileLine = null;
System.out.println("TEST 1: Contents of file are as follows: ");
while (klg.hasNextInt()) { //Puts file contents into string
fileLine = klg.nextLine();
System.out.println(fileLine);
}
System.out.println("");
System.out.println("TEST 2 BELOW");
String strArr[] = fileLine.split(" "); //temporary array to hold all numbers and split
for(int i = 0; i < strArr.length; i++){ //Trying to split String into individual elements and put into string array.
System.out.print(strArr[i] + " ");
}
System.out.println("");
System.out.println("--------");
for(int k = 0; k < strArr.length;k++) {
b[k] = strArr[k]; //Assigns contents into 3 arrays
l[k] = strArr[k];
d[k] = strArr[k];
System.out.println(b[k]);
System.out.println(l[k]);
System.out.println(d[k]);
}
输出:
TEST 1: Contents of file are as follows:
200 1000 800
450 845 1200
800 250 400
0 1500 1800
600 500 1000
700 1400 1700
675 400 900
TEST 2 BELOW
675 400 900
--------
675
675
400
400
900
900
最佳答案
使用一个 3x7 矩阵和两个 for
循环,分别保存每个 int
值:
File input = new File("Lab1File.txt");
Scanner scanner = new Scanner(input);
int[][] matrix = new int[7][3];
for(int i = 0; i < 7; i++)
{
for(int j = 0; j < 3; j++)
{
matrix[i][j] = scanner.nextInt();
}
}
scanner.close();
关于java - 我有一个包含 3 列和 7 行的文件,我需要从文件中的每一列中创建 3 个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35096543/