Reputation: 45
My requirement is to take multiple inputs from user on multiple lines.
Each line signifies inputs with meanings of : Power Energy Idea Strength
each separated by just one space.
Input:
2 4 5 7
3 4 8 1
4 2 3 6
Output consists of List:
List<Integer> power = {2,3,4}
List<Integer> energy = {4,4,2}
List<Integer> idea = {5,8,3}
List<Integer> strength = {7,1,6}
preferred solution is in Java, but if Java-8 solutions can be given i would love it.
i have tried so far as below but no luck:
String input = "";
Scanner keyboard = new Scanner(System.in);
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
System.out.println(input);
i am able to read input in multiple lines but not able to save them as separate category in List
.
Upvotes: 1
Views: 864
Reputation: 170
U can input as much values as u want with this program:
List<Integer> power = new ArrayList<>();
List<Integer> energy = new ArrayList<>();
List<Integer> idea = new ArrayList<>();
List<Integer> strength = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(true) {
String s = sc.nextLine();
if(s.equals("exit")) break;
String args = s.split(" ");
if(args.length >= 4) {
power.add(Integer.valueOf(args[0]));
energy.add(Integer.valueOf(args[1]));
idea.add(Integer.valueOf(args[2]));
strength.add(Integer.valueOf(args[3]));
}
}
Upvotes: 0
Reputation: 15906
You can simply split the line and put the value in separate lists:
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
String arr[] = line.split(" ");// spiting the line based on space
if (arr.length==4) { // check if length is 4 as you are expecting
// use Integer.valueOf() to convert from string to Integer
power.add(arr[0]);
energy.add(arr[1]);
idea.add(arr[2]);
strength.add(arr[3]);
}else {
//throw exception or break
}
input += line + "\n";
}
Regarding how to use java 8 stream API in System.in check How to build a Java 8 stream from System.in / System.console()?
Upvotes: 2