没有打印出来

Mar*_*ark 0 java

我是编程新手,我遇到了一些麻烦.基本上我要做的是让findCar方法循环通过名为cars的LinkedList并让它打印出汽车对象的ID.它会编译但是没有打印出来,有人可以解释一下为什么会这样吗?

这是主要课程

import java.io.*;
import java.util.*;

public class CarManger {
private LinkedList<Car> cars = new LinkedList<Car>(); 

public void setup()

{   
cars.add(new Car(1));
cars.add(new Car(2));
cars.add(new Car(3));   
}

public void main() {

    char choice;
    while ((choice = readChoice()) !='x' ) {
        switch(choice) {
            case 'a': findCar(); break;
        }
    }
}

private char readChoice() {
    System.out.print("Your choice: ");
    return In.nextChar();
}

public void findCar()
  {
    for (Car i: cars)
   { 
    int value = i.getId();
    System.out.println(value);
   } 
  }

 }
Run Code Online (Sandbox Code Playgroud)

这是汽车对象

public class Car {

private int id;

public Car(int id) 
{
    this.id = id;
}

public int getId() {
    return this.id;
} 
}
Run Code Online (Sandbox Code Playgroud)

这里是用于收集输入的In类

import java.util.*;

public class In
{ private static Scanner in = new Scanner(System.in);

public static String nextLine()
{   return in.nextLine(); }

public static char nextChar()
{   return in.nextLine().charAt(0); }

public static int nextInt()
{   int i = in.nextInt();
    in.nextLine();
    return i;   }

public static double nextDouble()
{   double d = in.nextDouble();
    in.nextLine();
    return d;   }
Run Code Online (Sandbox Code Playgroud)

这也是修订后的代码

  import java.io.*;
  import java.util.*;

  public class CarManger {
   private LinkedList<Car> cars = new LinkedList<Car>(); 


  public static void main(String [ ] args) {

    CarManager carManager = new CarManager();
     }

public CarManager () {

    setup();
    main();

}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 6

您的setup()方法永远不会被调用,因此没有汽车似乎被添加到您的汽车列表中.

请注意,您的main方法需要是静态的并且具有一个Strings数组参数(除非这不是您的程序的起点main方法).如果没有main方法,程序将编译,但不会运行.

我建议你创建一个有效的main方法:

public static void main(String[] args) {

}
Run Code Online (Sandbox Code Playgroud)

并在里面创建一个CarManager对象,调用setup()它等等......

注意:如果我有一个调用的方法findCar(),我可能会接受一个参数,这里,最好的参数可能是一个int来表示Car的id号,我声明方法返回一个Car对象,并在里面方法体,我会搜索一个id与方法参数匹配的Car.方法签名看起来像这样:

public Car findCar(int id) {
   // TODO: 
   // write code to loop through the cars list 
   // if we find a car whose getId() matches our parameter id int
   // return it!
} 
Run Code Online (Sandbox Code Playgroud)

您的主要方法如下所示:

public static void main(String[] args) {
    CarManager carManager = new CarManager();

    // here you'd call methods on carManager
    // for instance if CarManager had an addCar(...) method

    Car car = new Car(4);
    carManager.addCar(car);
}
Run Code Online (Sandbox Code Playgroud)

请注意,我不会调用您当前的setup()方法,或者readChoice()因为它们看起来不对我,但是如果没有您的特定分配要求,则很难猜测.