EDIT:
I am trying to add elements read from a txt document line by line into an array list then convert that array list into an array. Although I am getting errors with my code. It doesnt like the int[] a = lines.toArray(new int[lines.size()]);.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
List<Integer> lines = new ArrayList<Integer>();
File file = new File("10_Random.txt");
try {
Scanner sc = new Scanner(file);
//int line = null;
while (sc.hasNextLine()) {
int i = sc.nextInt();
lines.add(i);
//System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
int[] a = lines.toArray(new int[lines.size()]);
}
}
Edit2: Thanks chaitanya10! all fixed.
“null is a special literal that can be of any object reference type”.you cant assign
nulltoprimitive variablesin java like (int, byte, float…).null can only be assigned to objects . remember thatnullis the default vale forobjects` when you don’t initialize them.if you wanna access int as an object use
Integer.and to convert an list onto array do this.
List.toArray(T[] t) method returns an Object.
do like below.
and also your List accepts int[] array and you are tryig to add an int into the list .
change your List declaration like this
To print the elements in the array you have to iterate over it
you seem to be a beginner in java. strongly recommend you tohereread about java basic