I was trying to make a code to answer to another person's problem... and I came out with another problem.
The idea would be a program that asks you to input numbers so it sorts them and prints them out from higher to lower.
This is what I came with:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input: ");
Integer input = new Integer(Integer.parseInt(scanner.nextLine()));
scanner.close();
Integer[] numbers = new Integer[input.toString().length()];
for (Integer value : numbers) {
while (input > 1) {
value = input % 10;
input /= 10;
}
}
Arrays.sort(numbers, Collections.reverseOrder());
int a = 0;
for (Integer value : numbers) {
if (a < numbers.toString().length()) {
System.out.print(value + ", ");
a++;
} else {
System.out.println(value + ".");
}
}
}
But, being Input: 292816374
the input, this is what the console says:
Exception in thread "main" java.lang.NullPointerException
at java.util.Collections$ReverseComparator.compare(Unknown Source)
at java.util.Collections$ReverseComparator.compare(Unknown Source)
at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at StartingPoint.main(StartingPoint.java:21)
The problem is that it is trying to sort null
integers, but I don't know why it detects numbers
as a null array when it's already been initialized.
If I change the Integer
s to int
s there aren't exceptions, but it prints out zeroes.
Why does this happen?