我試圖獲取用戶輸入的某個文本文件中的最大值。我也把它分成不同的方法。繼承人是我到目前爲止有:在java中輸入文本文件中查找最大值
public static void FindMax(String file)throws IOException{
int maximum = 0;
Scanner fileScanner = new Scanner(new File(file)); {
int big = fileScanner.nextInt();
while (fileScanner.hasNextInt()) {
int num = fileScanner.nextInt();
if(num > big) {
maximum++;
System.out.println(num);;
}
}
}
}
public static void main(String[] args)throws IOException{
Scanner keyboard = new Scanner(System.in);
String file;
System.out.print("Enter file: ");
file = keyboard.nextLine();
FindMax(file);
}
輸出打印文本文件中的所有內容,除了第一個值,而不是打印最大。例如,如果文本文件是:
1
2
3
4
5
它只打印2,3,4和5,我不知道我why.How可以得到最大值? Id感謝任何幫助/建議。提前致謝。
編輯:你們所有人都在說類似的解決方案,但是當我嘗試它們時,它只是打印相同的輸出。我很困惑。
有在你的代碼中的邏輯錯誤。你想要做的是從文本和文件中讀取一個數字,並比較它是否大於以前的最大數字。如果是,請更新最大值,然後檢查下一個數字。在讀完整個文件後,你應該打印最大變量的值 – amyn