gpt4 book ai didi

java - 从文本文件添加并忽略语法错误

转载 作者:太空宇宙 更新时间:2023-11-04 12:01:11 27 4
gpt4 key购买 nike

我正在编写一个代码,将文本文件中的数字相加并显示总数。但我想让它这样,如果用户输入一个单词或一个十进制数字,那么它会忽略它并继续添加下一个数字?

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Task1 {
public static void main(String [] args) throws FileNotFoundException {
File myFile = new File("Numbers.txt");
Scanner scan = new Scanner(myFile);

int sum=0;

while (scan.hasNext()) {
sum+= scan.nextInt( );
}
System.out.println(sum);

scan.close();

}
}

最佳答案

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Task1 {
public static void main(String [] args) throws FileNotFoundException {
File myFile = new File("Numbers.txt");
Scanner scan = new Scanner(myFile);

String sum="";
int number = 0;
int total = 0;
while (scan.hasNext()) {
try {
sum = scan.next();
number = Integer.parseInt(sum);
total += number;
} catch(Exception e) {
System.out.println("Unable to parse string !! + " + sum);
}
}
System.out.println("The total is : " + total);

scan.close();

}
}

关于java - 从文本文件添加并忽略语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40892604/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com