Reputation: 609
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-->0)
{
int n=sc.nextInt();
ArrayList <Integer> arr=new ArrayList<Integer>();
for(int i=0; i<n; i++)
{
arr.add(sc.nextInt());
}
System.out.println(arr);
}
}
I already know the size of the ArrayList. I also saw other questions, but they read using the hasNext(), when the size is unknown. How do I do it this way, when the array size is previously known? I just wanted to use inbuilt functions like rotate() and hence I want to create this. But this just doesn't work. it adds nothing to the list. I even tried reading as an array and using Collections.addAll to put to a new ArrayList, but that also isn't working. When I tried to convert after reading as an array to ArrayList that is giving me other errors. I also tried reading as an integer variable and adding into the list without directly inserting. That gives me just one element inserted. I don't know why.
Edit: It was an error in inputting from my part. It's solved.
Upvotes: 0
Views: 101
Reputation: 2812
By using scan.nextLine()
you can get multiple numbers in the same line, instead of inputting them one-by-one by calling, scan.nextInt()
. This is showcased in the code below:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static Integer[] convertToIntArray(String[] arr) {
int index = 0;
Integer[] numbers = new Integer[arr.length];
for (int i = 0; i < arr.length; ++i) {
try {
numbers[index] = Integer.parseInt(arr[i]);
++index;
} catch (NumberFormatException nfe) {
// This part skips invalid input, which is not a number.
// by not saving the skipped element to the array.
}
}
return numbers;
}
public static void main(String[] args) {
// Get the line containing numbers from the user.
System.out.println("Input numbers: ");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
// Split sentence into words.
String[] arr = s.split("\\W+");
// Convert string array of numbers to int.
Integer[] numbers = convertToIntArray(arr);
System.out.println(Arrays.toString(numbers));
}
}
When run with an input of 10 numbers this outputs:
Input numbers:
1 2 3 4 5 6 7 8 9 10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Upvotes: 1