我得到了一个由数字
组成的data.txt文件12 45 345 500 45.67684 33
执行 readData 方法后,它应该只打印整数值和打印元素对任何其他类型无效,然后继续这样
readData("data.txt") 将打印以下内容:12 45 345 500 元素无效 33
我的问题是,一旦打印了元素无效语句,我的代码就不会继续打印 33,它只是在 12 45 345 500 元素无效处停止
import java.io.*;
import java.util.*;
public class Ex7 {
public static void readData(String nameFile){
try{
BufferedReader br = new BufferedReader(new FileReader(nameFile));
String line = br.readLine();
int i = 0;
while((line != null)){
try{
String[] lines = line.split(" ");
int[] result = new int[lines.length];
result[i] = Integer.parseInt(lines[i]);
if(result[i] ==(int)result[i]){
System.out.print(result[i] + " ");
}
i++;
}
}
}catch(NumberFormatException e){
System.out.println("element not valid " );
}catch(IOException e){
System.out.println("IO error");
System.exit(0);
}
}
public static void main (String[] args){
readData("data.txt");
}
}
我建议不要使用异常,而是检查它是否是一个数字。异常速度很慢,应仅用作回退。查看此链接以获取有关数字字符串的更多信息,或搜索Google以获取其他方式。数值的
您提问的原因是您不了解发生的控制流。
这很简单:你有一个从文件中读取的循环。但你的渔获物在这个循环之外。因此,当有东西抛出并且您在循环外"接住"时,该循环就"结束"了;没有办法回去。
所以,直接的答案是:移动 try/catch for NumberFormatException ...到它实际可能发生的一个地方。
try {
result[i] = Integer.parseInt(lines[i]);
} catch (NumberFormatException ...
但是当然...这直接导致了代码的下一个问题:您正在使用数组来存储"有效"输入......数组具有固定大小。你怎么知道提前有多少成员是有效的?你没有。因此:您必须从使用数组更改为动态列表,例如 ArrayList。现在,您只需添加"有效"行即可。但是,无论如何,这并不重要。因为您的方法没有返回收集的值。但是,如果不使用数据;首先收集它是没有意义的。
除了你必须做的代码更改之外,答案是:回到书本;并了解你正在使用的结构/概念是如何实际工作的。盲目键入 try/catch 是没有意义的,因为它们出现在某个地方,或者因为您的 IDE 告诉您需要以某种方式对异常执行一些操作。意思是:当你写下代码时...确保您真正了解此代码在做什么。你知道,就像其他声明if (result[i] == (int) result[i])
...这永远是真的;而且根本没有任何意义。
将 NumberFormatException 放在 While 应该可以工作。
public static void readData(String nameFile){
try{
BufferedReader br = new BufferedReader(new FileReader(nameFile));
String line = br.readLine();
int i = 0;
while((line != null)){
try{
String[] lines = line.split(" ");
int[] result = new int[lines.length];
result[i] = Integer.parseInt(lines[i]);
if(result[i] ==(int)result[i]){
System.out.print(result[i] + " ");
}
i++;
}catch(NumberFormatException e){
System.out.println("element not valid " );
}
}
}catch(IOException e){
System.out.println("IO error");
System.exit(0);
}
}
将捕获 NumberFormatException 的 catch 块放在循环中,但也要考虑 @Христо Стайков 给出的答案。
使用以下代码:
public static void readData(String nameFile) {
try {
BufferedReader br = new BufferedReader(new FileReader(nameFile));
String line = br.readLine();
String[] lines = line.split(" ");
int[] result = new int[lines.length];
for(int i=0;i<lines.length;i++){
try{
result[i] = Integer.parseInt(lines[i]);
if(result[i] ==(int)result[i]){
System.out.print(result[i] + " ");
}
}catch(NumberFormatException nfe){
System.out.println("Number Invalid");
}
}
}catch(Exception ex){
ex.printStackTrace();
}
}