【发布时间】:2014-12-09 23:23:47
【问题描述】:
我确实需要帮助解决我正在处理的问题。我试图在 .txt 文件中找到最大和最小数字,它可以是任何数字,它只需要读取文件然后打印出最大和最小数字。 readfile 工作正常,唯一的问题是我只能得到 0 的答案。
我的代码:
import java.util.Scanner;
import java.io.*;
public class LargeSmall
{
public static void main(String[] args) throws IOException
{
//gets filename
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of the file: ");
String filename = keyboard.nextLine();
//opens file
File file = new File(filename);
Scanner inputFile = new Scanner(file);
//place holders for varibales
int val = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
//to read all lines of file
while (inputFile.hasNext())
{
//gets min and max number
int number = inputFile.nextInt();
if ( val > max)
{
max = val;
}
if ( val < min)
{
min = val;
}
}
//Close file
inputFile.close();
//Print out lowest value in the list and highest
System.out.println("Min number is: " +min);
System.out.println("Max number is: " +max);
}
}
不明白我做错了什么,任何提示或帮助将不胜感激!
【问题讨论】: