简体   繁体   中英

how to take inputs seperated by new line

I have an input with the line breaks. I want to convert that string into an array, and for every new line, jump one index place in the array.

If the input is:

100
200
300

Then I need the output to be:

110
210
310

I have used the following code:

public class NewClass {
    public static void main(String args[]) throws IOException {
        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
        String str=br.readLine();
        String [] arrOfStr = str.split("\n");int b=0;
        for (String a : arrOfStr) {
            b=Integer.parseInt(a);
            int c=b+10;
            System.out.println(c);
        }
     }
}

But it is not giving the desired output. Note : We are not taking the input from text file. We don't know how many inputs are there in test case. We have take inputs in one go.

You could use a scanner.hasNext() instead as -

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    // scanner.useDelimiter("\\r\\n"); // if required to delimit the input 
    while (scanner.hasNext()) {
        int c = Integer.parseInt(scanner.next()) + 10;
        System.out.println(c);
    }
}

Using the same Input as yours -

 100 200 300 

The Output would be -

 110 210 310 

To elaborate on my comment.

    List<Integer> intList = new ArrayList<Integer>();
    BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
    String str = br.readLine();
    while (!str.isEmpty()) {
        intList.add(Integer.parseInt(str)+10);
        str=br.readLine();

    }
    System.out.println(intList);}

This should work, I'm on my phone...

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