Reputation: 169
How would I read a single "line" of input from the user that seperates the values by space and assign them to a certain variable? Seems quite confusing for me.
For example,
Enter 3 digits = 3 4 5
Total = 12
The input that I put, once there is a space, only prints first value when I put "3 4"
I know I should not use nextInt scanner but I can't figure out a way
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Enter 3 digits:");
a = scan.nextInt();
System.out.println(a);
Upvotes: 2
Views: 113
Reputation: 21981
By doing sum in for loop:
Scanner scan = new Scanner(System.in);
System.out.println("Enter 3 digits:");
int sum=0;
for(int i=0;i<3;i++){
sum = sum + scan.nextInt();
}
System.out.println(sum);
Upvotes: 2
Reputation: 135
If you are required to read all integers in one read you can use this code. If reading one by one is ok the refer to other answers. For this code you can make a loop and use arrays as well.
String a;
Scanner scan = new Scanner(System.in);
System.out.println("Enter 3 digits:");
a = scan.nextLine();
Scanner stscan = new Scanner(a);
System.out.println(a);
int number1 = stscan.nextInt();
int number2 = stscan.nextInt();
int number3 = stscan.nextInt();
System.out.println(number1+number2+number3);
Upvotes: 1
Reputation: 36476
You just call nextInt()
2 more times.
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
Upvotes: 1
Reputation: 7796
It would be best to have an array of variables, and read integers into the array one at a time like this:
int[] a = new int[3];
Scanner scan = new Scanner(System.in);
System.out.print("Enter 3 digits: ");
for(int i = 0 ; i < a.length ; i++) //loop 3 times
{
a[i] = scan.nextInt(); //get int from input
System.out.println(a[i]);
}
scan.nextLine(); //consume the \n
Upvotes: 1