如何计算文本文件(Java)中的整数数量?

时间:2016-02-11 21:50:31

标签: java

我需要编写一个计算Java文本文件中整数数量的程序。如果存在偶数个整数,程序应成对读取整数并打印出两个数字的最大值。例如,如果文本文件具有整数6 2 5 9,则Java应打印出6 9。如果有一个奇数的整数,它应该打印一条错误信息。

我得到了打印出最大值的程序,但我无法弄清楚如何计算整数的数量。该程序编译,但运行一个空白屏幕。我做错了什么?

我的代码是:

import java.io.*;
import java.util.Scanner;
public class Lab1_Reading_Files {
   public static void main (String[] args) throws FileNotFoundException {
      Scanner reader = new Scanner(new File("integers.txt"));
      int count = 0;
      int max = 0;
      int num1;
      int num2;
      while (reader.hasNextInt()) {
         count++;
      }
      if (count % 2 == 0) {
         while (reader.hasNextInt()) {
            num1=reader.nextInt();
            num2=reader.nextInt();
            if (num1>num2){
               max=num1;
            }
            else if (num2>num1) {
               max=num2;
            }
            System.out.print(max+" ")
         }
      }
      else  {
         System.out.println("The File has an odd number of Integers");
      }          
   }
}

1 个答案:

答案 0 :(得分:3)

下面:

  while (reader.hasNextInt())  {        
     count++;
  } 

如果reader.hasNextInt()为真,那将永远属实,你的程序永远不会离开这个循环......

工作版本:

import java.io.*;
import java.util.Scanner;

public class Lab1_Reading_Files       {

  public static void main (String[] args)throws FileNotFoundException {

      Scanner reader = new Scanner(new File("integers.txt"));    
      int count=0;
      int max=0;
      int num1;
      int num2;   

      while (reader.hasNextInt())  {        
         num1=reader.nextInt();
         count++;
         if (!reader.hasNextInt()) {
             System.out.println("The File has an odd number of Integers");
             break;
         }
         num2=reader.nextInt(); 
         count++;        

         if (num1>num2) max = num1;
         else           max = num2;

         System.out.println(max + " ");
      }
      System.out.println("The file had " + count + " number(s)");
   }
}