我已经在这个程序上工作了一段时间了,我一直在努力解决这个问题。我是编程新手,所以我不明白如何解决它。到目前为止,我已经设法消除了大部分错误,但这是我由于某种原因无法修复的错误。有人能帮我吗?我真的很感激。
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);
}
}
}
下面是宠物类
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;
}
}