我必須在文本檔案的每一行中找到最大的數字,但由于某種原因,我的代碼只能在第一行中找到最大的數字。
File file = new File("input.txt");
Scanner sc = new Scanner(file);
int highScore = sc.nextInt();
while(sc.hasNextInt()){
int grade = sc.nextInt();
if(grade > highScore){
highScore = grade;
}
}
System.out.println(highScore);
sc.close();
我嘗試了很多東西,但它只在第一行找到最大的數字。文本檔案中的數字采用 4x4 樣式,因此第一行:4 10 2,第二行:11 5 20,第三行:6 3 5
uj5u.com熱心網友回復:
給定以下文本行。
String text = """
1 2 3 4 5 6
30 20 1 30 40
9 100, 4, 5 12 1
""";
- 用于
Pattern.splitAsStream(String)僅流式傳輸數值。正則運算式\\D將拆分任何非數字分組。(感謝Alexander Ivanchenko提供的替代方案Arrays.stream(String.split,regex) - 過濾掉任何空字串并轉換為 int。
- 然后回傳最大值。注意:由于
max回傳一個OptionalInt你需要使用getAsInt()來獲取值。
Scanner sc = new Scanner(text);
while(sc.hasNextLine()) {
int highScore = Pattern.compile("\\D ")
.splitAsStream(sc.nextLine())
.filter(s->!s.isBlank())
.mapToInt(Integer::parseInt)
.max().getAsInt();
System.out.println(highScore);
}
印刷
6
40
100
出于演示目的,使用了文本字串。當您打開檔案并使用掃描儀讀取時,while 回圈也應該起作用。
uj5u.com熱心網友回復:
用于hasNextLine()了解何時讀取新行以重置最高分數。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class ScanLine {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("input.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()) {
String line = sc.nextLine();
String[] nums = line.split(" ");
int highScore = 0;
for(int i = 0; i < nums.length; i) {
int grade = Integer.parseInt(nums[i]);
if(grade > highScore){
highScore = grade;
}
}
System.out.println(highScore);
}
sc.close();
}
}
uj5u.com熱心網友回復:
如檔案hasNextInt()中所述,如果此掃描儀輸入中的下一個標記可以解釋為 int 值,則方法回傳 true。
如果您有這樣的輸入:
4 10 2,
11 5 20
6 3 5
Token 2,不能解釋為 int 值,對于這個 token 方法hasNextInt()會回傳false,你會存在 while 回圈。在那之前,您會發現最大的數字是數字 10,這就是您在控制臺上看到的數字
uj5u.com熱心網友回復:
File aaa = new File("input.txt");
Scanner sc = new Scanner(aaa);
int highScore = sc.nextInt();
int counter=1;
while(sc.hasNextInt()){
int grade = sc.nextInt();
if(counter%3==0){
highScore = grade;
}
if(grade > highScore){
highScore = grade;
}
counter;
if(counter%3==0){
System.out.println("highScore= " highScore " in line number " counter/3);
}
}
sc.close();
注意:如果每行中有 3 個值,則此代碼有效,您可以通過更改此條件計數器%3==0 將 3 更改為任意數字來更改它
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505062.html
