我正在尝试创建一个大小为[3]和[100]的二维数组,这个想法是它将存储三个字符串,这些字符串将存储在由制表符分隔的文本文件中。我已经在网上搜索了任何帮助,但没有找到任何好的答案。它需要是一个通过Java存储的数组。
它应该是这样的:
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]);
}
}
}
答案 0 :(得分:1)
几点:
请参阅代码中的注释,说明它的作用:
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"
}
}
答案 1 :(得分:0)
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)
此外,您的变量应始终以小写字母开头,只有类应具有较大的首字母。