0
import java.util.Scanner;


public class Search {
    static Scanner scanner = new Scanner(System.in);
    static Scanner kb = new Scanner(System.in);
    static Scanner kb2 = new Scanner(System.in);
    public static void main (String[] args)
    {

        int choice;
        System.out.print("Choose a number of students: ");
        int n = scanner.nextInt();  
        String name[] = new String[n+1];
        String course[] = new String[n+1];
        int ID[] = new int[n+1];

        for(int i=1;i <= n; i++)
        {
            System.out.print("Enter ID number " + i + ": ");
            ID[i] = scanner.nextInt();
            System.out.print("Enter Student name " + i + ": ");
            name[i] = kb.nextLine();
            System.out.print("Enter Student course " + i + ": ");
            course[i] = kb2.nextLine();
            System.out.println("----------------------------------------");
        }

       
      
        do
        {
            choice = menu();
            if(choice == 1)
            {
                sortID(ID);
                printValues(ID);

            }else if(choice == 2)
            {
                nameSort(name,n);
                printName(name,n);
            }else if(choice == 3)
            {

            }
        }while(choice !=0);
    }

    public static int menu()
    {
        System.out.print("\n1. Sort by ID\n2. Sort by Name\n3. Search by ID\n4. Search by Name\n5. Search by Course\n6. Display Records In table Form.\nYour Choice: ");
        return scanner.nextInt();
    }

    public static void sortID(int []id)
    {
        int temp;
        int index, counter;
        for (counter=0; counter < id.length -1; counter++) {
            for (index=0; index < id.length - 1 - counter; index++) {
                if (id[index] > id[index+1]) {
                    temp = id[index];
                    id[index]=id[index+1];
                    id[index+1]=temp;
                }
            }
        }
    }

    public static void printValues (int[]array) {
        
        System.out.println ("\nSorted Id Number: ");
        for(int i = 1; i < array.length; i++){
            System.out.print ("\n" + array[i]);            
        }
            
    }

    public static void printName (String[]array,int a) {
        
        for (int i = 0; i <= a - 1; i++) 
        {
            System.out.print(array[i] + ", ");
        }
            
    }

   public static void nameSort(String[] name,int a)
    {
        String temp;
        for (int i = 0; i < a; i++) 
        {
            for (int j = i + 1; j < a; j++) { 
                if  (name[i].compareTo(name[j])>0) 
                {
                    temp = name[i];
                    name[i] = name[j];
                    name[j] = temp;
                }
            }
        }
    }






}

The sorting works on the id but i have problems in my names it wont push through the bubble sort and say its null, im just starting learning this language and it would be a great help. Ive been working on this since last night and ive tried transffering it under the if else(choice == 2) still it says null.

Choose a number of students: 2 Enter ID number 1: 123 Enter Student name 1: Mark JAw Enter Student course 1: JSJS ---------------------------------------- Enter ID number 2: 221 Enter Student name 2: Ak akw Enter Student course 2: jdj ----------------------------------------

1. Sort by ID
2. Sort by Name
3. Search by ID
4. Search by Name
5. Search by Course
6. Display Records In table Form.
Your Choice: 1

Sorted Id Number:

123
221
1. Sort by ID
2. Sort by Name
3. Search by ID
4. Search by Name
5. Search by Course
6. Display Records In table Form.
Your Choice: 2
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.compareTo(String)" because "name[i]" is null
        at Search.nameSort(Search.java:95)
        at Search.main(Search.java:41)
PS C:\Users\Bingus\Documents\Projects> 
Dean Yankee
  • 29
  • 1
  • 6
  • 3
    You should not have three scanners all pointing to System.in. That's a bug waiting to pounce. – NomadMaker Mar 24 '21 at 01:49
  • im gonna change that one too, the only problem was that the sort by name wont work – Dean Yankee Mar 24 '21 at 01:50
  • You should include the full stack trace. Or is this a compiler error? – NomadMaker Mar 24 '21 at 01:51
  • what is a full stack trace? – Dean Yankee Mar 24 '21 at 01:52
  • @DeanYankeeJabili Copy and paste what your program prints. Make sure to include everything. – Spectric Mar 24 '21 at 01:52
  • where can I paste this one? – Dean Yankee Mar 24 '21 at 02:03
  • I posted it already in the lower part – Dean Yankee Mar 24 '21 at 02:04
  • I don't have the ability to run / debug your code right now, but I see that you may be having some issues with your array indexes. You are allocating your arrays one element too large, and that, along with starting your indexes at 1 instead of 0 may be most or all of your problem. So, allocate your arrays as size "n", not "n+1", and always iterate your arrays from index 0, so, e.g. `for(int i=0;i < n; i++)`. This may not entirely fix your problem, but it's good, first, necessary step. Then debug from there. – GreyBeardedGeek Mar 24 '21 at 02:11
  • 2
    Okay, so the error says that you can't do the thing you want to do because something is null. Did you try to figure out why it's null? Did you try to change the code so that it isn't null any more? – Karl Knechtel Mar 24 '21 at 02:13
  • 1
    Hint: if you do `String name[] = new String[n+1];` and `n` is equal to `3`, what do you think `name` will become? How many elements will it contain? What will the initial values be? What will it look like after you store 3 strings in it? Where you have written `for(int i=1;i <= n; i++)`, what do you think will be the values of `i` used in that loop? What do you think are the valid indices for `name`? Does that match up? – Karl Knechtel Mar 24 '21 at 02:18
  • Please read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/, and also try to ask yourself why you made the choices you did previously in your code. – Karl Knechtel Mar 24 '21 at 02:18
  • thank you so much,ill try and change something in the code – Dean Yankee Mar 24 '21 at 02:21
  • It works now @KarlKnechtel thank you so much, i really do need to just change it up and now i understand why it does that – Dean Yankee Mar 24 '21 at 02:25
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Johannes Kuhn Mar 24 '21 at 02:28

1 Answers1

0
String name[] = new String[n+1];

Suppose for example that you read in a value of 3 for n. This code means that you will allocate 3+1 = 4 elements in name (and likewise in the other arrays). You do not want to allocate 4 elements. You will read 3 names, so you want to allocate 3 elements.

The valid indices for your array will be 0, 1, 2 and 3. You do not want 3 to be a valid index for your array. You want only 0, 1 and 2 to be valid indices, which if you count, you will notice makes 3 different indices.

for(int i=1;i <= n; i++)

In this loop, you will use values of 1, 2 and 3 for i, and thus assign to indices 1, 2 and 3 of name (as well as the other arrays). You do not want to do this. The result is that name[0] will remain null. You want to start the loop at 0 so that you use every element of the arrays. You want to use i < n as your loop condition, because once you correctly only have n elements in the array, n is no longer a valid index.

    for (int i = 0; i < a; i++) 
    {
        for (int j = i + 1; j < a; j++) { 
            if  (name[i].compareTo(name[j])>0) 

When the exception happens, it happens because you correctly start scanning the array from the beginning, but have incorrectly filled (and sized) the array. You pull a null value out of the array (that shouldn't be there) and try to .compareTo another value (which doesn't work, because you can't call a method on a null). A similar problem would occur (if you got that far) in your other sorting method.

(Unless it is for an assignment, you should not implement sorting yourself. You should use java.util.Arrays.sort.)

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153