[英]Storing input from text file
我的问题很简单,我想读入一个文本文件并将文件中的第一行存储为一个整数,并将文件的其他每一行存储到一个多维数组中。 我想这样做的方法是创建一个 if 语句和另一个整数,当该整数为 0 时,将该行存储到整数变量中。 虽然这看起来很愚蠢,但肯定有更简单的方法。
例如,如果文本文件的内容是:
4
1 2 3 4
4 3 2 1
2 4 1 3
3 1 4 2
第一行“4”将存储在一个整数中,每隔一行将进入多维数组。
public void processFile(String fileName){
int temp = 0;
int firstLine;
int[][] array;
try{
BufferedReader input = new BufferedReader(new FileReader(fileName));
String inputLine = null;
while((inputLine = input.readLine()) != null){
if(temp == 0){
firstLine = Integer.parseInt(inputLine);
}else{
// Rest goes into array;
}
temp++;
}
}catch (IOException e){
System.out.print("Error: " + e);
}
}
我不是故意回答这个来为你做的。 尝试一些东西:
String.split
array[temp-1] = new int[firstLine];
Integer.parseInt
行的内部for
循环这应该足以让你走完剩下的路
相反,您可以将文件的第一行存储为一个整数,然后进入一个 for 循环,您可以在其中循环文件的其余行,将它们存储在数组中。 这不需要if
,因为您知道第一种情况首先发生,其他情况(数组)发生在之后。
我将假设您知道如何使用文件 IO。 我不是很有经验,但这是我的想法:
while (inputFile.hasNext())
{
//Read the number
String number = inputFile.nextLine();
if(!number.equals(" ")){
//Do what you need to do with the character here (Ex: Store into an array)
}else{
//Continue on reading the document
}
}
祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.