读取TXT文件和存储整数到一个数组 [英] Read integers from txt file and storing into an array
本文介绍了读取TXT文件和存储整数到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有问题读,从文本文件中存储的整数。我使用的,所以我想这样做没有列表中的int数组。我得到一个输入匹配例外,我不知道我应该怎么去纠正这个问题。从还包括字符串读取的文本文件。
公共静态整数[] readFileReturnIntegers(字符串文件名){
整数[]数组=新的整数[1000];
INT I = 0;
//连接到文件
档案文件=新的文件(文件名);
扫描仪INPUTFILE = NULL;
尝试{
INPUTFILE =新的扫描仪(文件);
}
//如果没有文件中发现错误消息
赶上(FileNotFoundException异常除外){
的System.out.println(找不到文件!);
}
//如果连接,读取文件
如果(INPUTFILE!= NULL){
System.out.print(文件中\\整数数目,
+文件名+\\= \\ n);
//通过阵列文件整数和储存环
而(inputFile.hasNext()){
数组[我] = inputFile.nextInt();
我++;
}
inputFile.close();
}
返回数组;
}
解决方案
您可以使用这样的事情(跳过任何非INT(S)),并应关闭扫描仪
!
//如果连接,读取文件
如果(INPUTFILE!= NULL){
System.out.print(文件中\\整数数目,
+文件名+\\= \\ n);
//通过阵列文件整数和储存环
尝试{
而(inputFile.hasNext()){
如果(inputFile.hasNextInt()){
数组[我] = inputFile.nextInt();
我++;
}其他{
inputFile.next();
}
}
} {最后
inputFile.close();
}
//我想你想打印。
的System.out.println(ⅰ);
为(中间体V = 0; V族I; v ++){
System.out.printf(数组内容[%d =%d个\\ N,V阵列[V]);
}
}
I'm having issues reading and storing only integers from a text file. I'm using a int array so I want to do this without list. I'm getting a input mismatch exception, and I don't know how I should go about correcting that issue. The text files being read from also include strings.
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] array = new Integer[1000];
int i = 0;
//connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
//If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
//if connected, read file
if(inputFile != null){
System.out.print("number of integers in file \""
+ filename + "\" = \n");
//loop through file for integers and store in array
while (inputFile.hasNext()) {
array[i] = inputFile.nextInt();
i++;
}
inputFile.close();
}
return array;
}
解决方案
You might use something like this (to skip over any non-int(s)), and you should close your Scanner
!
// if connected, read file
if (inputFile != null) {
System.out.print("number of integers in file \""
+ filename + "\" = \n");
// loop through file for integers and store in array
try {
while (inputFile.hasNext()) {
if (inputFile.hasNextInt()) {
array[i] = inputFile.nextInt();
i++;
} else {
inputFile.next();
}
}
} finally {
inputFile.close();
}
// I think you wanted to print it.
System.out.println(i);
for (int v = 0; v < i; v++) {
System.out.printf("array[%d] = %d\n", v, array[v]);
}
}
这篇关于读取TXT文件和存储整数到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文