+ 1
Need ideas for parsing user input string into 3 integers?
I would like to parse user input of "1-12-3" into 3 integers that are saved as variables for calculations. any hints would be appreciated. I have thought of array groups or pattern matching. My starting point is a scanner that I have posted. https://code.sololearn.com/c0NF3HTNpUV0/?ref=app
4 Answers
+ 5
Just an idea on counting input entries, you can check whether if there's a "-" (dash) in the input, since it's a delimiter, if none, treat the input as a single entry, otherwise split the input.
+ 3
Here's an example of one way you could do it:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class Program
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();
for(String num: sc.nextLine().split("-")) {
numbers.add(Integer.parseInt(num));
}
for(Integer num: numbers) {
System.out.println(num);
}
}
}
+ 1
Thanks these are just what I was looking for but hadn't learned yet. I especially like how if I input 1-12-3 I get a 3 array list, but if a input 1000 I get a 1 item list. Perfect for accepting either and then using them. Now I'll start on what I will do with the numbers. :)