Reputation: 37
I'm working on a java assignment and was stuck on this part. Basically we are to get the user to input three positive non-zero integers using the scanner.
It's supposed to look something like this
Enter three integer values: 2 2 10
The numbers (2, 2, 10) cannot form a triangle.
I was wondering how can I code it so that entering the "2 2 10" could be read as three different integers that are separated by a comma. Thank you very much in advance.
Upvotes: 1
Views: 5473
Reputation: 66
You can make it as follows:
String sentence = scanner.nextLine();
And you can make:
String[] splittedByComma = sentence.split(",");
Or by space:
String[] splittedBySpace = sentence.split(" ");
Or an array list like the following example:
How to split a comma-separated string?
Then parse each of them to integers.
Upvotes: 0
Reputation: 3489
Read the input with java.util.Scanner
and a for loop:
Scanner sc = new Scanner(System.in);
int[] values = new int[3];
for (int i = 0; sc.hasNextInt() && i < 3; i++) {
values[i] = sc.nextInt();
}
Upvotes: 1
Reputation: 2670
scanner.nextInt is your answer
final BufferedReader input = new BufferedReader(
new InputStreamReader(System.in));
// enter yours 2 2 10 and press Enter
final String line = input.readLine();
final Scanner s = new Scanner(line);
int a = s.nextInt(); // reads 2
int b = s.nextInt(); // reads 2
int c = s.nextInt(); // reads 10
if (a + b > c || a + c > b || b + c > a ) {
System.out.println(
"No triangle can be composed from " + a + ", " + b + ", " + c );
}
Upvotes: 0
Reputation: 39
Try this:
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
String[] inValues = line.split(" ");
int[] values = new int[inValues.length];
for(int i = 0; i < inValues.length; i++){
values[i] = Integer.parseInt(inValues[i]);
}
Upvotes: 0