我需要编写一个程序来计算 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/