【问题标题】:How to put the name of another java file (or class) next to the name of a method?如何将另一个 java 文件(或类)的名称放在方法名称旁边?
【发布时间】:2018-03-05 22:55:46
【问题描述】:

我的教授列出了我应该编写或更改的方法。其中之一是她列为 Customer getCustomer(String n)。现在 customer 是另一个 java 文件的名称,稍后将使用它来使代码正常工作,但我几乎可以肯定 getCustomer 是我应该创建该方法的名称。下面我将复制并粘贴为此方法编写的代码,然后发布编译错误。请帮我编译这段代码。

public void Customer getCustomer(String username){
   for(int i=0; i<customerList.size(); i++){
   String holdingSpotForArrayEle;
   holdingSpotForArrayEle = customerList.get(i); 
   if (holdingSpotForArrayEle == username)
   return username;
   }
   }

你看到这里的第一行代码就是错误所在。

编译错误如下:

CustomerDatabase.java:77: error: '(' expected
   public void Customer getCustomer(String username){
                        ^
1 error

(顺便说一下,小胡萝卜符号位于 getCustomer 中的 g 下方。) 如果您正在考虑摆脱客户,那么教授通过将方法称为 Customer getCustomer(String n) 将客户包含在方法的开头。

【问题讨论】:

  • public void Customer getCustomer(String username){ 你定义了 2 种返回类型
  • 教授。为您提供了要使用的确切方法签名:Customer getCustomer(String n) {...}
  • 另外,不要使用== 来比较字符串。代替holdingSpotForArrayEle == username,使用holdingSpotForArrayEle.equals(username)
  • 方法getCustomer 应该返回一个Customer,所以之前的void 没有意义。因为现在 java 认为您正在声明一个名为 Customer 且没有返回类型 void 的方法,并且在它之后应该有一个 ( 但它遇到了 getCustomer 令牌。所以它说 g 处的错误。你真正想要的是没有void

标签: java arraylist methods count compiler-errors


【解决方案1】:
public void Customer getCustomer(String username)

是方法的错误签名。

同时查看代码中的 return 语句

return username; // check type of username

当前签名将返回String,这也是username 的类型:

public String getCustomer(String username)

为了返回类型Customer,你的方法定义应该被更新以使用:

return new Customer(); // just for example

然后匹配的方法签名将是

public Customer getCustomer(String username)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    相关资源
    最近更新 更多