I have file that has n lines of Integers. I want to add each int in each line and print them (so I should print 3 int at the end, each one for a line).
I tried this but it will read and add all the Integers in the first loop.
scan = new Scanner(new BufferedReader(new FileReader("input.txt")));
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
while (scan.hasNextLine()) {
sum += scan.nextInt();
}
System.out.println(sum);
sum = 0;
}
This behavior is caused by erroneous usage of loops and scans. One of correct solutions also incorporates java 8 lambdas, with the assumption that the delimiter of the integers in the file is space(" "):
Path path = Paths.get("your path");
try{
Files.lines(path)
.map( line -> line.split(" "))
.mapToInt( numbers -> Arrays.stream(numbers)
.reduce(0 , (sum, num) -> sum + Integer.parseInt(num), (first, second) -> first + second ))
.forEachOrdered(System.out::println);
} catch (IOException e){
e.printStackTrace();
}
I think I could do this too...
read = new Scanner(new BufferedReader(new FileReader("input.txt")));
int n = read.nextInt(), j;
int sum = 0;
for (int i = 0; i < n; i++)
{
String[] str;
int t = read.nextInt();
// First str will be ""(it reads the end of each line)
str = read.nextLine().split(" ");
// Then it can read what we want
str = read.nextLine().split(" ");
for (j = 0; j < str.length; j++)
{
sum += Integer.parseInt(str[j]);
}
System.out.println(sum);
sum = 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.