java读取txt文件。显示每行旁边的整数之和,并找出其中最大的和
45 90 40 30 42 95 64 47 23
148030842449161020
我是Java OOP的初学者
这是Txt文件。我必须在每行旁边打印整数之和
然后找出其中最大的一个
我能读这个文件
我试着把每一行都做成一个字符串
我尝试将每一行都设为Int
但当我将行中的每个数字设为整数时。
我无法确定如何在列结束时停止程序,以便打印总和并转到下一行
import java.util.Scanner;
import java.io.*;
public class Asst1Problem2{
public static void main(String[] args){
int sum = 0;
int largestSum = 0;
String line = "";
try{
Scanner input = new Scanner(new File("integers2.txt"));
while(input.hasNextLine()){
line = input.nextLine();
System.out.println(line);
}
}
catch(FileNotFoundException fnf){
System.out.print("no file " + fnf);
}
}
}
我希望得到总数,但我没有得到正确的答案
# 1 楼答案
您好,您可以使用循环或流(Java8+)解决这个问题。我还建议您使用try-with-resources
如果没有流,您可以使用以下示例
For more details regarding the check if a string is an integer
对于java-8+流,以下代码应该可以做到这一点:
# 2 楼答案