okay so I am a beginner at java and I am implementing a class which stores an array and sorts it using bubble sort.
import java.io.*;
public class Array
{
private int array[];
private int n;
private BufferedReader br;
public Array() throws IOException
{
System.out.print("Enter the size of the array : ");
br=(new BufferedReader(new InputStreamReader(System.in)));
n = Integer.parseInt(br.readLine());
System.out.println("Enter "+ n +" integers");
for(int i=0;i<n;i++)
{
array[i]=Integer.parseInt(br.readLine());
}
}
public void showArray()
{
int i;
for (i=0; i<n;i++)
{
System.out.print(array[i]+" ");
}
}
public void bubbleSort()
{
int max,last,i,j;
last = n;
for(i = 0; i<n ; i++)
{
max=0;
for(j=0; j<last; j++)
{
max = (array[max]>array[j]) ? max : j ;
}
j = array[last];
array[last] = array[max];
array[max] = j;
last--;
}
}
public static void main(String [] args) throws IOException
{
Array a1 = new Array();
System.out.println("Unsorted Array : ");
a1.showArray();
System.out.println("Sorted Array : ");
a1.bubbleSort();
a1.showArray();
}
}
so when I run it it gives the error :
shubham@shubham-Inspiron-3542:~$ java Array
Enter the size of the array : 4
Enter 4 integers
11 9 7 16 4
Exception in thread "main" java.lang.NumberFormatException: For input string: "11 9 7 16 4"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Array.<init>(Array.java:16)
at Array.main(Array.java:48)
I am totally not getting what's the issue. What I can guess is there is some issue while parsing the input stream. edit: when I press Enter after an input I get this :
shubham@shubham-Inspiron-3542:~$ java Array
Enter the size of the array : 5
Enter 5 integers
22
Exception in thread "main" java.lang.NullPointerException
at Array.<init>(Array.java:16)
at Array.main(Array.java:48)
edit 2: Splitting the input stream gets rid of NumberFormatException error but NullPointerException error is still there