我一直在寻找答案,但似乎可以找到答案。如何仅打印此Arraylist
中tailLength
等于或高于用户指定值的对象?如果竞赛等于tax
,则tailLength
应自动设置为3.7
。我有一个问题,想弄清楚如何做到这一点。正如您所看到的,我有一种方法可以检查竞争是否为tax
,如果没有,则计算尾部的长度。
所以我的问题基本上是,如何让这项工作成功?我想在我的方法中检查竞争是否为tax
,并且我还想打印出arraylist
中具有与用户指定值相等或更高的值的对象。到目前为止,这是我的两个班级:
PS。我知道我必须添加一些东西才能完成这项工作,但我一直在寻找几个小时而无法找到答案。
import java.util.ArrayList;
import java.util.Scanner;
public class MainProgram
{
public static void main(String[] args)
{
ArrayList<Dog> doglist = new ArrayList<Dog>();
Scanner myscan = new Scanner(System.in);
boolean running = true;
while(running)
{
System.out.println("\n************************************");
System.out.println("\nVälkommen till Kennelklubben!");
System.out.println("\n************************************");
System.out.println("\n[1] Register new dog");
System.out.println("[2] Print out list");
System.out.println("[3] Increase age");
System.out.println("[4] Remove dog");
System.out.println("[5] Quit program");
System.out.println("\n************************************");
System.out.println("\nChoose: ");
int option = myscan.nextInt();
switch (option)
{
case 1:
System.out.println("Write name:");
String name = myscan.next();
System.out.println("Write race:");
String race = myscan.next();
System.out.println("Age:");
int age = myscan.nextInt();
System.out.println("Weight:");
double weight = myscan.nextDouble();
doglist.add(new Dog(name, race, age, weight));
break;
case 2:
System.out.println("Write minimum length of tail:");
double tail = myscan.nextDouble();
for (Dog name1 : doglist)
{
System.out.println(name1.toString());
}
break;
public class Dog
{
private String name;
private String race;
private int age;
private double weight;
private double tailLength;
public Dog (String name, String race, int age, double weight)
{
this.name = name;
this.race = race;
this.age = age;
this.weight = weight;
}
public double tailLength()
{
if (race=="tax")
tailLength = 3.7;
else
tailLength=(age-weight)/10;
return tailLength;
}
public String toString()
{
return name + " " + race +
" " + age + " " + "år" + " " + weight + " " + "kg" + " " + tailLength;
}
}
答案 0 :(得分:0)
我认为您应该更改Dog
类的位构造函数。我建议在构造函数中初始化tailLength
变量:
public Dog (String name, String race, int age, double weight) {
this.name = name;
this.race = race;
this.age = age;
this.weight = weight;
if(race.equals("tax")) {
this.taillength = 3.7;
} else {
this.tailLength = (age - weight) / 10;
}
}
就我没有误解你的问题而言,我认为在你的case 2
中你应该遍历Dog
的每个dogList
个实例。使用&#34; if&#34;声明您检查存储在dog tailLength
变量中的值,如果它高于tail
(用户输入的值),则将该狗打印到控制台:
case 2:
System.out.println("Write minimum length of tail:");
double tail = myscan.nextDouble();
for(Dog d : doglist) {
if(d.tailLenght >= tail) {
System.out.println(d); /* You don't need to use d.toString() to print to the console,
when you use variable's name in the method printing out to the console, it
automatically uses its toString() method. */
}
}
break;