我正在尝试创建一个大小为[3]和[100]的2d数组,其想法是它将存储三个字符串,这些字符串将存储在一个用tab分隔的文本文件中。我已经在网上搜索了任何帮助,但没有找到任何好的答案。它需要是一个通过Java存储的数组。
应该是这样的:
- 将字符串文件与filename.txt关联
- 创建一个大小为3列和100行的2d数组。在这里,它应该从左到右存储数据,每行有3个字符串,然后分离到新行
- 那么我需要一种方法将文本文件中的字符串添加到数组中。最后它应该打印数组的内容
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class ArrayDirectory {
public static void main(String args[]) {
String file = ("directory.txt");
// initialises the file linked to the String file
String[][] Entry = new String[3][50];
// creates a 2d array with 3 columns and 50 rows.
readFromFile.openTextFile(file);
//should read from file
String line = readFromFile.readLine();
int count = 0;
while (line != null) {
input[count] = String.split("");
Entry = readFromFile.readline();
}
for (int h = 0; h < input.length; h++) {
System.out.println(input[h]);
}
}
}
几点:
- 你没有办法阅读这份文件
- 当您的注释与之相反时,您的数组有3行50列
- 你试图在一个空格上拆分,而不是在一个选项卡上拆分
请参阅代码中解释其作用的注释:
public class ArrayDirectory {
public static void main(String args[]) throws FileNotFoundException {
String file = ("lab4b2.txt");
Scanner scan = new Scanner(new FileReader(file));
// initialises the scanner to read the file file
String[][] entries = new String[100][3];
// creates a 2d array with 100 rows and 3 columns.
int i = 0;
while(scan.hasNextLine()){
entries[i] = scan.nextLine().split("t");
i++;
}
//loops through the file and splits on a tab
for (int row = 0; row < entries.length; row++) {
for (int col = 0; col < entries[0].length; col++) {
if(entries[row][col] != null){
System.out.print(entries[row][col] + " " );
}
}
if(entries[row][0] != null){
System.out.print("n");
}
}
//prints the contents of the array that are not "null"
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ArrayDirectory{
public static void main(String args[]) throws IOException {
BufferedReader readFromFile = new BufferedReader(new FileReader("test.txt"));
int count = 0;
String[][] entry = new String[100][3];
String line = readFromFile.readLine();
while (line != null) {
//I don't know the layout of your file, but i guess it is: "XX YY ZZ", with spaces inbetween.
String[] temp = line.split(" "); //temp here will be: [XX][YY][ZZ]
for (int i = 0; i < temp.length; i++) {
entry[count][i] = temp[i];
}
line = readFromFile.readLine();
count++;
}
readFromFile.close();
for (int j = 0; j < entry.length; j++) {
for (int k = 0; k < entry[0].length; k++) {
System.out.print(entry[j][k] + " ");
}
System.out.println();
}
}
}
在此处阅读有关字符串拆分的信息:http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String(
此外,变量应该总是以小写字母开头,只有类的第一个字母应该是大的。