Reputation: 19
hi i am trying to get these fruits in alphabetical order can someone help please as when i try to run the program it closes and says NullPointer Exception java Lang but it compiles no problem i think the problemis with the .compareTo line i am not too sure
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Write a description of class rigthOrder here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class rigthOrder
{
public static void main (String args []) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int i;
String fruit [] = new String[1000];
List<String> fruitsList = Arrays.asList (fruit);
fruit[0] = "orange";
fruit[1] = "bananna";
fruit[2] = "apple";
fruit[3] = "grape";
fruit[4] = "plum";
// for(i = 0; i < fruit.length; i++)
{
// fruit [i] = fruit [i].toUpperCase();
}
Bubble_sort(fruit);
for(i = 0; i < fruit.length; i++)
{
System.out.println(fruit [i]);
}
}
public static void Bubble_sort(String [] fruit)
{
int i, j, size = fruit.length;
String temp;
for(i = 0; i < size-1; i++)
{
for(j = i + 1; j < size; j++)
{
if (fruit[j].compareTo (fruit[i]) < 0)
{
temp = fruit[i];
fruit[i] = fruit [j];
fruit[j] = temp;
}
}
}
}
}
Upvotes: 0
Views: 350
Reputation: 476
In addition to the rest of the answers, you can also declare the array in a static way:
String[] fruit = new String[] {"orange", "bananna", "apple", "grape", "plum"}
That way the size is automatically calculated.
Upvotes: 0
Reputation: 1303
you are declaring an array of size 1000
String fruit [] = new String[1000];
then filling five of those 1000 slots
fruit[0] = "orange";
fruit[1] = "bananna";
fruit[2] = "apple";
fruit[3] = "grape";
fruit[4] = "plum";
what is in the rest ?
Upvotes: 0
Reputation: 16310
You made an array of 1000 elements, and only filled in 5 of them.
String fruit [] = new String[1000];
Make this array the proper length and it will stop failing.
Upvotes: 0
Reputation: 117675
String fruit[] = new String[1000];
The default values of String
array's elements are null
. That's why Arrays.asList(fruit)
throws NPE.
Upvotes: 1