[英]How to create a multidimensional Array to take input from .txt file and store the strings and the numbers separate
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"
}
}
How do I make the following code to split the string into pieces and store them in the multidimentional array? 如何编写以下代码将字符串拆分为多个片段并将其存储在多维数组中? For example:
例如:
Text: 文本:
123 abc 456 123 abc 456
789 def 101 112 789 def 101112
array 数组
[123] [abc] [456] [123] [abc] [456]
[789] [def] [101] [112] [789] [def] [101] [112]
The numbers from the text being converted to numbers before stored in the array. 将文本中的数字转换为数字,然后再存储在数组中。 I believe I have to use Integer parsed.Int().
我相信我必须使用Integer parsed.Int()。 not sure how to implement it
不确定如何实施
With the following corrections, you would end up with the entries array with the splitted strings correctly. 经过以下更正,您将最终获得带有正确分割字符串的entrys数组。
public static void main(String args[]) throws FileNotFoundException
{
String file = ("C:\\array.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())
{
String [] splittedEntries = new String[3];
splittedEntries = scan.nextLine().split(" ");
for( int inx = 0; inx < splittedEntries.length; ++inx )
{
entries[i][inx] = splittedEntries[inx];
}
i++;
}
}
At this moment, your entries array would look like this: 此时,您的entrys数组将如下所示:
entries[0] = { 123, abc, 456 };
entries[1] = { 789, def, 101 };
So, you can write your own loops now and process as required. 因此,您可以立即编写自己的循环并按要求进行处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.