I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first intege
Using this on many coding sites:
Suppose you are given 3 test cases with each line of 4 integer inputs separated by spaces 1 2 3 4
, 5 6 7 8
, 1 1 2 2
int t=3,i;
int a[]=new int[4];
Scanner scanner = new Scanner(System.in);
while(t>0)
{
for(i=0; i<4; i++){
a[i]=scanner.nextInt();
System.out.println(a[i]);
}
//USE THIS ARRAY A[] OF 4 Separated Integers Values for solving your problem
t--;
}
CASE 2: WHEN NUMBER OF INTEGERS in each line is NOT GIVEN
Scanner scanner = new Scanner(System.in);
String lines=scanner.nextLine();
String[] strs = lines.trim().split("\\s+");
Note that you need to trim() first: trim().split("\\s+")
- otherwise, e.g. splitting a b c
will emit two empty strings first
int n=strs.length; //Calculating length gives number of integers
int a[]=new int[n];
for (int i=0; i<n; i++)
{
a[i] = Integer.parseInt(strs[i]); //Converting String_Integer to Integer
System.out.println(a[i]);
}
i know it's old discuss :) i tested below code it's worked
`String day = "";
day = sc.next();
days[i] = Integer.parseInt(day);`
If you know how much integers you will get, then you can use nextInt()
method
For example
Scanner sc = new Scanner(System.in);
int[] integers = new int[3];
for(int i = 0; i < 3; i++)
{
integers[i] = sc.nextInt();
}
When we want to take Integer as inputs
For just 3 inputs as in your case:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
For more number of inputs we can use a loop:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a[] = new int[n]; //where n is the number of inputs
for(int i=0;i<n;i++){
a[i] = scan.nextInt();
}
Better get the whole line as a string and then use StringTokenizer to get the numbers (using space as delimiter ) and then parse them as integers . This will work for n number of integers in a line .
Scanner sc = new Scanner(System.in);
List<Integer> l = new LinkedList<>(); // use linkedlist to save order of insertion
StringTokenizer st = new StringTokenizer(sc.nextLine(), " "); // whitespace is the delimiter to create tokens
while(st.hasMoreTokens()) // iterate until no more tokens
{
l.add(Integer.parseInt(st.nextToken())); // parse each token to integer and add to linkedlist
}