I just started programming in java (yesterday as a metter of fact) and I'm messin' around trying to learn the basics. So I decided that I wanted to read a string, save the words in an array of strings and then sort that array and output it sorted. Here's the code for it:
package project2;
import java.util.Scanner;
class First
{public static void main(String args[])
{ Scanner scan=new Scanner(System.in);
Second obj=new Second(2,3);
String s; // the string
String word[]=new String[10]; // the array of strings
int n=0; // the number of elements in the array
System.out.print("String: ");
s=scan.nextLine();
System.out.printf("This is the string: %s\n", s);
for(String i : s.split("[,. ]") )
{word[n]=i;
n++;}
for(int j=0; j<word.length;j++) //1
{for (int i=j+1 ; i<word.length; i++)
{if(word[i].compareTo(word[j])<0)
{String temp= word[j];
word[j]= word[i];
word[i]=temp;}}} //2
System.out.print("The sorted string is: ");
for(int i=0;i<n;i++)
System.out.print(" "+word[i]);
}}
Now, when I try to run it for the input:
aa bb cc
I get the error:
Exception in thread "main" aa bb cc java.lang.NullPointerException at project2.First.main(First.java:20)
Now the error comes from within 1 and 2, but I can't figure out what causes the error.