I've been working on this program for sometime now and I've been struggling with it. I'm new to programming so I don't understand how to fix it. So far I've managed to get rid of most of the errors but this one is the one I, for some reason, cannot fix. Can someone help me? I would really appreciate it.
import java.util.Scanner;
import java.util.ArrayList;
public class PetSorter
{
public static void main (String [] args)
{
ArrayList<Pet> strList = new ArrayList<Pet>();
Boolean another = true;
Scanner keyboard = new Scanner(System.in);
while(another)
{
System.out.println("Enter the pet's name: ");
String nam = keyboard.nextLine();
Pet p = new Pet(nam); //here is where the Error occurs
strList.add(p);
System.out.println("Would you like to enter another pet's name? (y/n)");
String answer = keyboard.nextLine();
another = answer.equalsIgnoreCase("y");
}
PetSorter.nameSort(strList);
for (int x = 0; x < strList.size(); x++)
{
System.out.println(strList.get(x).getName());
}
}
public static void nameSort (ArrayList<Pet> array)
{
for (int i = 1; i < array.size(); i++)
{
int j = i;
Pet tp = array.get(i);
String B = array.get(i).getName();
while ((j > 0) && (array.get(j-1).getName().compareTo(B) > 0 ))
{
array.set(j, array.get(j-1));
j--;
}
array.set(j,tp);
}
}
}
Here is the pet class below
import java.util.ArrayList;
import java.util.Scanner;
public class Pet
{
private String name;
private int age; //in years
private double weight; //in pounds
/**
This main is just a demonstration program.
*/
public static void main(String[] args)
{
Pet myDog = new Pet( );
myDog.set("Fido", 2, 5.5);
myDog.writeOutput( );
System.out.println("Changing name.");
myDog.set("Rex");
myDog.writeOutput( );
System.out.println("Changing weight.");
myDog.set(6.5);
myDog.writeOutput( );
System.out.println("Changing age.");
myDog.set(3);
myDog.writeOutput( );
}
public void writeOutput( )
{
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Weight: " + weight + " pounds");
}
public void set(String newName)
{
name = newName;
//age and weight are unchanged.
}
public void set(int newAge)
{
if (newAge <= 0)
{
System.out.println("Error: illegal age.");
System.exit(0);
}
else
age = newAge;
//name and weight are unchanged.
}
public void set(double newWeight)
{
if (newWeight <= 0)
{
System.out.println("Error: illegal weight.");
System.exit(0);
}
else
weight = newWeight;
//name and age are unchanged.
}
public void set(String newName, int newAge, double newWeight)
{
name = newName;
if ((newAge <= 0) || (newWeight <= 0))
{
System.out.println("Error: illegal age or weight.");
System.exit(0);
}
else
{
age = newAge;
weight = newWeight;
}
}
public String getName( )
{
return name;
}
public int getAge( )
{
return age;
}
public double getWeight( )
{
return weight;
}
}