简体   繁体   中英

Java- Code snippet to scan the below input with multiple test cases and multiple values in each test case

I have a requirement to perform an operation in java(say addition for making it simpler) on a set of positive integer values(any number/s).

The sample input where the first line gives the count of testcases , the below lines are the respective testcases with any number of positive integers .

Input:

3
67 8 12
3 6 9 78 6
4 6 13

Output:

87
102
23

First you need to read file, lets use the Files.readAllLines . Next you'll need to read first line, convert it to int , and now you know how much jobs (or testcases) should be executed. Next using for loop on jobs count, and get every next line from file. Split it by space and loop over all values, convert them to int and summarize them.

Code:

import java.util.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

class base_class {
  public static void main(String[] args) {
    try {
        List<String> lines = Files.readAllLines(new File("file.txt").toPath());
        int jobs = Integer.parseInt(lines.get(0));
        for (int j = 1; j <= jobs; j++) {
            String line = lines.get(j);
            String[] integers = line.split(" ");
            int result = 0;
            for (int i = 0; i!= integers.length; i++) {
                result += Integer.parseInt(integers[i]);
            }
            System.out.println(line + " => " + result);
        }
    } catch (IOException e) {
        System.out.println("File error, " + e);
    }
  }
}

file.txt:

4
67 8 12
3 6 9 78 6
4 6 13
2 10 41

PS Next time when you ask question please add your tries/code that specifies your attempts to solve the thing you're asking.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM