使用数组进行用户输入

时间:2016-03-11 03:27:42

标签: java arrays

我已经四处寻找答案,但我找不到它。我的教授要求我使用数组..而不是arraylist

public static void main(String[] args) {
    final int total = 30;
    String[] animalType = new String[total];
    Scanner input = new Scanner(System.in);

    for (int x = 0; x < total; x++) {
        System.out.println("Enter the type of animal " + x + 1);
        animalType[x] = input.next();

        for (int x1 = 0; x1 < total; x1++) {
            System.out.println("Enter the weight of the animal " + (x1 + 1));
            animalType[x1] = input.next();
        }

        input.close();

        System.out.println("Your friends are");
        for (int counter = 0; counter < total; counter++) {
            System.out.println(animalType[counter] + "\n" + animalType[counter]);
        }
    }
}

提示符是..允许用户输入动物的类型和动物的体重,然后按动物类型输出平均体重。 我是java的新手,不知道如何正确使用数组。

2 个答案:

答案 0 :(得分:1)

我认为你应该为此目的创建一个类。

首先,创建另一个名为Animal.java的文件并编写一个存储typeweight的类:

public class Animal {
    public String type;
    public int weight;
}

当然,如果添加getter和setter会更好,但是我觉得这对你来说太难了。无论如何我都会显示代码,但我不会在下面的例子中使用它。

public class Animal {
    private String type;
    private int weight;

    public String getType() {return type;}
    public void setType(String value) {type = value;}

    public int getWeight() {return weight;}
    public void setWeight(int value) {weight = value;}
}

现在你有了这个类,你可以创建它的数组。

Animal[] animals = new Animal[total];

你需要用动物填充阵列!

for (int i = 0 ; i < total ; i++) {
    animals[i] = new Animal();
}

实际上,你的for循环是错误的。如果你想首先询问用户类型,然后是重量,你应该这样做:

for (int x = 0; x < total; x++) {
    System.out.println("Enter the type of animal " + x + 1);
    animals[x].type = input.next();
}

for (int x1 = 0; x1 < total; x1++) {
    System.out.println("Enter the weight of the animal " + (x1 + 1));
    animals[x1].weight = Integer.parseInt(input.next());
}

现在你得到了动物的种类和重量,万岁!

答案 1 :(得分:0)

您需要第二个数组来存储重量。像

这样的东西
String[] animalWeight = new String[total];
for(int x1 = 0; x1 < total; x1++){
    System.out.println("Enter the weight of the animal "+(x1+1));
    animalWeight[x1] = input.next();  
}

接下来,打印两个数组中的值。我希望调用println 两次来嵌入\n(在一些也可能导致问题的系统上,因为它们使用其他行终止字符,例如\r\n )。这可能看起来像,

// input.close(); // <-- Also closes System.in, can cause subtle bugs.
System.out.println("Your friends are");
for(int counter = 0; counter < total; counter++){
    System.out.println(animalType[counter]);
    System.out.println(animalWeight[counter]);
}