[英]Find biggest number in each row from a text file in java
我必須在文本文件的每一行中找到最大的數字,但由於某種原因,我的代碼只能在第一行中找到最大的數字。
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
使用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();
}
}
給定以下文本行。
String text = """
1 2 3 4 5 6
30 20 1 30 40
9 100, 4, 5 12 1
""";
max
返回OptionalInt
您需要使用getAsInt()
來獲取值。Scanner sc = new Scanner(text);
while(sc.hasNextLine()) {
int highScore = Arrays.stream(sc.nextLine().split("\\D+"))
.filter(s->!s.isBlank())
.mapToInt(Integer::parseInt)
.max().getAsInt();
System.out.println(highScore);
}
印刷
6
40
100
出於演示目的,使用了文本字符串。 當您打開文件並使用掃描儀讀取時,while 循環也應該起作用。
如文檔中所述,如果此掃描儀輸入中的下一個標記可以解釋為 int 值,則方法hasNextInt()
返回 true。
如果您有這樣的輸入:
4 10 2,
11 5 20
6 3 5
令牌2,不能解釋為 int 值,對於這個令牌方法hasNextInt()
將返回false
,你將存在 while 循環。 在那之前,您會發現最大的數字是數字 10,這就是您在控制台上看到的數字
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 更改為任意數字來更改它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.