到目前为止,我的代码看起来像这样:
public class CatWorld {
public static void main (String[] args) {
Scanner getLine = new Scanner(System.in);
String userSays;
//ARRAY:
int [] CatArray;
CatArray = new int [5];
//ARRAY-POWERED LOOP:
for (int i=0; i < CatArray.length; i ++) {
//OPTIONAL PROMPT:
System.out.println ("Wow! A brand new cat! What's its name?");
//Mandatory below
userSays = getLine.next();
Cat babyCat = new Cat(userSays);
System.out.println ("The new cat's name is "
+ babyCat.getcatName() + "!");
}
}
}
我的构造函数看起来像这样:
public class Cat {
String catName = "Billybob";
public Cat (String Name) { //Can also be birthName
catName = Name;
}
public String getcatName(){
return catName;
}
}
当我运行它时会发生什么,它是在我输入名称后立即输出的。在5个名字输入之后,我将如何输出它们?
答案 0 :(得分:1)
您需要以某种方式存储Cat
。
List<Cat> catList = new ArrayList<Cat>();
// Ask for cat names, and insert cat objects into list
然后在最后,
for (Cat cat : catList) {
// print whatever you want about the cats.
}
答案 1 :(得分:1)
经过测试并正常工作
将您main
方法中的代码更改为:
Scanner getLine = new Scanner(System.in);
String userSays;
Cat[] catList = new Cat[5]; // create array of 5 cats
int catCount = 0;
// loop to get all the user input for the cats
for (Cat cat : catList) // for each cat in cat array (5 cats)
{
System.out.println("Wow! A brand new cat! What's its name?");
userSays = getLine.next(); // get the cat name
catList[catCount] = new Cat(userSays); // set this cat in the cat array to be
// the user input
catCount++; // + the catCount, so the next cat in the cat array is focused on
}
// loop to display all of the cats back to the console
for (Cat cat : catList) // for each cat in the cat array
{
// display the cat's name in this iteration of the cat array
System.out.println ("The new cat's name is " + cat.getcatName() + "!");
}
答案 2 :(得分:0)
您必须将猫存储在您创建的阵列中。然后循环,然后在控制台中显示它们。
Cat[] catArray = new Cat[5];
for (int i=0; i < catArray.length; i ++){
System.out.println ("Wow! A brand new cat! What's its name?");
userSays = getLine.next();
catArray[i] = new Cat(userSays);
}
然后你再次循环:
for (int i=0; i < catArray.length; i ++){
System.out.println ("The new cat's name is "
+catArray[i].getcatName() + "!");
}
顺便说一下,你应该遵循java代码约定变量的名称以小写字母开头。
答案 3 :(得分:0)
int [] CatArray;
Cat[] catName = new String[5]; // Get cat names
CatArray = new int [5];
//ARRAY-POWERED LOOP:
for (int i=0; i < CatArray.length; i ++){
//OPTIONAL PROMPT:
System.out.println ("Wow! A brand new cat! What's its name?");
//Mandatory below
userSays = getLine.next();
catName[i] = new Cat(userSays);
}
for(int i = 0; i < catName.size; i++) {
System.out.println ("The new cat's name is "
catName[i].getcatName() + "!");
}