Exception in thread "main" java.lang.NumberFormatException: For input string: "150"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Long.parseLong(Long.java:711)
at java.base/java.lang.Long.parseLong(Long.java:836)
at Median.main(Median.java:45)
import java.io.*;
import java.util.*;
public class Median {
public static Long selection(ArrayList<Long> numbers, int k) throws IOException {
long pivot = numbers.get(0); //Line 8
ArrayList<Long> left = new ArrayList<Long>();
ArrayList<Long> middle = new ArrayList<Long>();
ArrayList<Long> right = new ArrayList<Long>();
for(int i = 1; i <= numbers.size(); i++) {
if(numbers.get(i) < pivot) {
left.add(numbers.get(i));
}
else if(numbers.get(i) == pivot) {
middle.add(numbers.get(i));
}
else {
right.add(numbers.get(i));
}
}
middle.add(pivot);
if(k <= left.size()) {
return selection(left, k);
}
else if(left.size() < k && k <= right.size()) {
return middle.get(0);
}
else {
return selection(right, k-left.size() - middle.size());
}
}
public static void main(String[] args) throws IOException {
ArrayList<Long> numsList = new ArrayList<Long>();
try(BufferedReader br = new BufferedReader(new FileReader("manhattanAirBnbPrivateRoomPrices.txt"))) {
String line = br.readLine();
String [] integers = line.trim().split("\n");
for(String integer: integers) {
numsList.add(Long.parseLong(integer)); // Line 45
}
} catch(IOException e) {
e.printStackTrace();
}
int position = numsList.size();
if((numsList.size() % 2) == 0) {
position = numsList.size() / 2;
}
else {
position = (int) numsList.size() / 2;
}
selection(numsList, position);
}
}
I've tried everything with Integer as the data type for everything (return type in selection method, ArrayList types, etc.) and it has the same error on line 45. I am reading from a text file using BufferedReader, but I tried using Scanner at first, but there was an ArrayIndexOutOfBounds error when trying to execute line 8 (long pivot = numbers.get(0);), so I switched it and that error went away, but came with this other one. What can I do to fix it, it sees like there's no way I can read the first line in the text file (150) because apparently its too large to be an integer and it just doesn't work when I changed everything to be of type long?!?!