java如何初始化用户输入的对象数组字符串值?
我有这类PetRecord:
public class PetRecord
{
private String name;
private int age;
private int weight;
public PetRecord(String initialName)
{
name = initialName;
age = 0;
}
public void set(String newName)
{
name = newName; //age and weight are unchanged.
}
public PetRecord(int initialAge)
{
name = "No name yet.";
weight = 0;
if (initialAge < 0)
{
System.out.println("Error: Negative age.");
System.exit(0);
}
else
age = initialAge;
}
public void set(int newAge)
{
if (newAge < 0)
{
System.out.println("Error: Negative age.");
System.exit(0);
}
else
age = newAge;
//name and weight are unchanged.
}
public PetRecord(double initialWeight)
{
name = "No name yet";
age = 0;
if (initialWeight < 0)
{
System.out.println("Error: Negative weight.");
System.exit(0);
}
else
weight = initialWeight;
}
public void set(double newWeight)
{
if (newWeight < 0)
{
System.out.println("Error: Negative weight.");
System.exit(0);
}
else
weight = newWeight; //name and age are unchanged.
}
public PetRecord()
{
name = "No name yet.";
age = 0;
weight = 0;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public double getWeight()
{
return weight;
}
}
我还有一个类,它使用PetRecord让用户输入有多少宠物,输入宠物的名字,然后按字母顺序对数组排序。我已经解决了排序部分(我想),但是我在设置每个PetRecord对象的名称时遇到了麻烦。我怎样才能解决这个问题
import java.util.Scanner;
public class PetSort {
public static void selectionSort(PetRecord[] a) {
for (int i = 0; i < a.length - 1; i++) {
// can add print statement here to help debug sorting algorithm:
System.out.print("In selectionSort: ");
for (int k = 0; k < a.length; k++)
System.out.print(a[k] + ", ");
System.out.println();
int indexOfMin = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j].getName().compareTo(a[indexOfMin].getName()) > 0)
indexOfMin = j;
}
PetRecord temp = a[i];
a[i] = a[indexOfMin];
a[indexOfMin] = temp;
}
}
public static void main(String args[]){
int i;
Scanner s = new Scanner(System.in);
System.out.println("How many pets are there?");
i = s.nextInt();
PetRecord[] array = new PetRecord[i];
System.out.println("Please give the names of the pets: ");
for (int k = 0; k < array.length; k++){
// This is the line that I'm trying to step through the array, and set the name of each PetRecord Object to what the user inputs.
//PetRecord array[i] = new PetRecord(s.nextLine());
}
selectionSort(array);
}
}
# 1 楼答案
首先要解决您的问题,您应该测试程序的逻辑,并清理代码,使其更有条理:
此外,你还有另一件事要做,彼得雷科德的施工人员应该:
在类中定义了实例变量:
因此,应该将参数化构造函数的参数类型与实例变量相同:
如果您想像这样重载构造函数,也可以:
最后,只需将
set
和get
方法更正为实例变量的相同数据类型# 2 楼答案
您需要在循环中插入
println
消息,否则用户可能不知道需要输入多少次所需的数据此外,循环中不需要整条线:
这样就可以了:
注意-用于
array
的索引器是k
而不是i
。如果使用i
对预定义数组进行索引,则会出现IndexOutOfBoundsException
异常例如: