0

I am a first year programming student and I am stuck on a question for one of my labs. I have played around with this little program for ages but I can't find the bug. I've used the debugger and looked through this forum for ideas but I've come up empty handed.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String pet;
    String pets[] = new String[5];
    int i=0;


    System.out.println("Enter the type of pet you own or type 'quit' to finish:");
    pet = input.nextLine();
    while(i<pets.length && pet.equalsIgnoreCase("quit") == false){
        pets[i] = pet;
        i++;
        if(i==5)
        {
            System.out.println("Maximum of five reached:");
        }
        else
        {
            System.out.println("Enter the type of pet you own or type 'quit' to finish:");
            pet = input.nextLine();
        }
    }
    for(i=0; i<pets.length; i++){
        if(pets[i].equals("null")==false){
        System.out.println(pets[i]);
        }
    }
    input.close();
}

This is the question that I have been asked. I only include this because it dictates the type of loop that I have to use.

"Write a program that uses a loop to ask the user to enter the type of pet they own.(maximum of 5 pets allowed ) They need to enter “quit” to stop entering data. The pets are stored in an array. Use for loop to display the pets in the array."

I appreciate any help I can get.

Schming
  • 51
  • 7
  • The reason i have the if(pets[i].equals("null")==false) line in there is because it was printing out the array fine, but was printing out "null" if less than 5 pets had been stored in the array – Schming May 06 '16 at 13:37
  • You error is because of how you are checking for that null. Null is not a string, therefore you don't check it like that. Check for nulls by saying this: `if(pets[i] != null)` – Rabbit Guy May 06 '16 at 13:42
  • 1
    That worked perfect. Thank you for that. I did think that null was a string. I appreciate your help. – Schming May 06 '16 at 13:47

0 Answers0