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

标签 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");
      }          
   }
}

最佳答案

这里:

  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)");
   }
}

关于java - 如何计算文本文件(Java)中的整数数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35350758/

相关文章:

java - 手动触发的 Azure Webjob 被多次触发。返回 409(冲突)错误

java - 使用 JPA 的事务边界和 DTO 转换

java - 如何创建全局查找上下文?

java - Servlet 充当代理 : How to forward the session?

java - 为什么 Java CRLF token 不适用于批处理文件输入?

java - 将联系人写入联系人数据库 - Android 2.1

java - JWrapper "unpack200.exe not found"

java - Eclipse 中的 Maven 依赖错误

java - Java 中的 C# 属性语法

java - 创建多个 "throwaway"对象是否影响性能