如何使用参数传递重载方法?

时间:2018-04-03 21:41:56

标签: java class methods parameters parameter-passing

我正在编写一个用户输入PC规格的程序,然后打印出这些规格。我有两个类,主类(PCSpecsDriver)和获取输入的类(PCSpecsClass)。

在PCSpecsClass中,我有一个名为“type”的重载方法,它基本上询问用户他们想要什么类型的笔记本电脑或台式机。它们都有不同的参数。但是,当我试图在驱动程序类中调用该方法时,它指向该参数并给了我这个错误:“找不到符号”。

我知道这可能是一个简单的答案,但我似乎无法弄明白。非常感谢!这是我的代码:

public class PCSpecsDriver {

  public static void main(String[] args) {

        Scanner kb = new Scanner(System.in);
        String answer;
        PCSpecsClass computer = new PCSpecsClass();

        do { 
              System.out.println("What kind of PC would you like to build(Laptop/Desktop)?"); 
              String response = kb.next();

              switch (response.toLowerCase()) {
                    case "desktop": 
                          computer.type(desktopResponse);
                          break;

                    case "laptop":
                          computer.type(laptopResponse);

                    default:
                          System.out.println("Not a valid response!");

              }

              System.out.println("Would you like to build another?");
              answer = kb.next();

        } while (answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("yes"));
  }




public class PCSpecsClass {


  Scanner kb = new Scanner(System.in);


  String laptopResponse;
  int desktopResponse; 

  public int type(int desktopResponse) {
        System.out.println("Type: Input 1 for laptop, 2 for notebook, 3 for tablet");
        return desktopResponse = kb.nextInt();
  }

  public String type(String laptopResponse) {
        System.out.println("Size: Input 1 for mini, 2 for medium, 3 for large");
        return laptopResponse = kb.nextLine();
  }

1 个答案:

答案 0 :(得分:0)

在Java中,您将变量/引用传递给方法。当你在switch case中调用computer.type()时,你试图为它提供PCSpecsDriver类中不存在的引用。 desktopResponselaptopResponse指的是不存在的值。对于初学者,重新访问Java(编辑:甚至不必是Java,范围是基本(不是语言)编程概念)教程,并查看本地和全局范围之间的区别。然后,重新考虑这个PCSpecs计划的设计。此外,在IDE中阅读错误消息。如果您已经这样做了,那么您就不会在这里。