我正在编写一个读入数字列表的程序。如:
45
63
74g
34.7
75
我只是希望我的程序跳过包含其中任何字母的行。任何帮助将不胜感激。谢谢!
如果它有所不同,这是我的代码:
import java.io.*;
public class ScoreReader {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
int num = Integer.parseInt(nums[i]);
if (num != -1) {
sum += num;
}
}
System.out.println(sum / nums.length);
}
} catch (IOException err) {
err.printStackTrace();
}
catch (NumberFormatException err) {
}
finally {
try {
if (reader != null)
reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
答案 0 :(得分:4)
抛出异常时,执行会跳转到catch块。在你拥有的内容中,这是在循环之后,因此循环不会继续,只需在try
附近添加parseInt
。
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
try{
int num = Integer.parseInt(nums[i]);
if (num != -1) {
sum += num;
}
} catch( NumberFormatException nfe )
{
// maybe log it?
}
}
System.out.println(sum / nums.length);
}
} catch (IOException err) {
err.printStackTrace();
}
// catch (NumberFormatException err) {}
finally {
try {
if (reader != null){
reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
另请注意,您使用的Integer.parseInt
会在输入"34.7"
处抛出异常,因此您可能希望使用Double.parseDouble
答案 1 :(得分:0)
使用正则表达式怎么样?例如:
if (currentLine.matches(".*[a-zA-Z].*")) {
//letters contained.
} else {
//no letters contained.
}
请参阅正则表达式演示:http://regex101.com/r/rQ6oR1
答案 2 :(得分:0)
你可以试试这个:
import java.io.*;
public class ScoreReader {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
if (isInt(num)) {
sum += num;
}
}
System.out.println(sum / nums.length);
}
} catch (IOException err) {
err.printStackTrace();
}
finally {
try {
if (reader != null)
reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
public boolean isInt(String num)
{
boolean flag=false;
try
{
int i=Integer.parseInt(num);
flag=true;
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
return flag;
}
}
答案 3 :(得分:0)
根据您的评论。如果您的文件每行包含一个数字。那么这将是最简单的方法。
Scanner sc = new Scanner(new File("QuizScores.txt"));
int sum = 0;
int count =0;
while( sc.hasNext()){
String tmpNum = sc.next();
if (isNumeric(tmpNum)){
sum = sum + (int) Double.parseDouble(tmpNum); // if you want t capture in double use Double instead.
count++;
}
}
System.out.println(sum/count);
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}