输入验证 - 只有整数?

时间:2015-10-24 02:31:50

标签: java

  

我正在开发一个Java代码必须找到总数的项目,   考试成绩的平均值等。它从外部读取分数   文件。

我一直在努力寻找一种方法来编辑我的代码,以便它忽略文件中不是0-100之间的整数的任何数据。但我不能。检查Stack Overflow上的所有问题和答案,我找不到任何有助于我的具体情况的答案。这是我尝试使用的代码的while循环:

Scanner reader = new Scanner(file);

   while (reader.hasNext())
   {
       String line = reader.nextLine();
       nextScore = Integer.parseInt(line);
       System.out.println(nextScore);
       sum = nextScore + sum;
       totalNumberOfScores++;



       if (nextScore > maxScore)
       {
           maxScore = nextScore;
       }

       else if (nextScore < minScore)
       {
           minScore = nextScore;
       }

       if (nextScore >= A)
       {
           countA++;
       }

       else if (nextScore >= B)
       {
           countB++;
       }

       else if (nextScore >= C)
       {
           countC++;
       }

       else if (nextScore >= D)
       {
           countD++;
       }

       else 
       {
           countF++;
       }
   }

    reader.close();

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

if(isInteger(line)){
  nextScore = Integer.parse(line);
}

public static boolean isInteger(String s) {
        try {
            Integer.parseInt(s);
        } catch(NumberFormatException e) {
            return false;
        } catch(NullPointerException e) {
            return false;
        }
        // only got here if we didn't return false
        return true;
    }

然后你可以这样做

boolean isNumber = false;
for(int i = 0; i < line.length; i++){
 try{
  Integer.parseInt(String.valueOf(line.charAt(i)));
 }catch(Exception e){
  isNumber = false;
  break;
 }
}
if(isNumber){
 Integer.parse(line);
}

甚至

boolean isNumber = true;
try{
 Integer.praseInt(line);
}catch(Exception e){
 isNumber = false;
}
if(isNumber){
 //everthing else
}

答案 1 :(得分:0)

通过阅读时,我会使用try-with-resources Statement close Scanner min。接下来,您需要在循环外定义maxtotallinesmin计数。您可以将max默认为最大可能值,将Math.max(int,int)默认为最小值;然后使用Math.min(int,int)int分别设置最大值和最小值。然后,在将其作为输入处理之前,您需要验证您是否读取了try (Scanner reader = new Scanner(file)) { int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int total = 0; int lines = 0; int countA = 0, countB = 0, countC = 0, countD = 0, countF = 0; while (reader.hasNextLine()) { String line = reader.nextLine(); try { int nextScore = Integer.parseInt(line); if (nextScore >= 0 && nextScore <= 100) { min = Math.min(nextScore, min); max = Math.max(nextScore, max); total += nextScore; lines++; if (nextScore >= A) { countA++; } else if (nextScore >= B) { countB++; } else if (nextScore >= C) { countC++; } else if (nextScore >= D) { countD++; } else { countF++; } } } catch (NumberFormatException nfe) { } } System.out.printf("Min: %d, Max: %d, Total: %d, Lines: %d, Average: %.2f%n", min, max, total, lines, total / (float) lines); System.out.printf("%d As, %d Bs, %d Cs, %d Ds, %d Fs", countA, countB, countC, countD, countF); } catch (IOException e) { e.printStackTrace(); } 并且它在正确的范围内。像,

{{1}}