-1

嘿伙计们,我是一个新手程序员,我得到了一个 .class 作为回报,但不知道它在问什么。任何帮助都会很棒,谢谢!

public static Letter[] addLetter(Letter[] array, Scanner kb)


{
      Letter[] temp = new Letter[array.length + 1];
      String toName, toAddress, toCity, toState, fromName, fromAddress, fromCity, fromState;
      int toZip, fromZip;
      double weight;

  for (int x = 0; x < array.length; x++){
     temp[x] = array[x];

     System.out.print("New Letter:\nTo Name: ");
     kb.nextLine();
     System.out.print("To Street: ");
     kb.nextLine();
     System.out.print("To City: ");
     kb.nextLine();
     System.out.print("To State: ");
     kb.nextLine();
     System.out.print("To Zip: ");
     kb.nextInt();
     kb.nextLine();
     System.out.print("From Name: ");
     kb.nextLine();
     System.out.print("From Street: ");
     kb.nextLine();
     System.out.print("From City: ");
     kb.nextLine();
     System.out.print("From State: ");
     kb.nextLine();
     System.out.print("From Zip: ");
     kb.nextInt();
     kb.nextLine();
     System.out.print("Letter weight: ");
     kb.nextDouble();
     kb.nextLine();

     Letter temp = new Letter(toName, toAddress, toCity, toState, toZip, fromName, fromAddress, fromCity, fromState, fromZip, weight);

     int x = array.length - 1;
     temp[x] = temp;
  }
  return temp[];

当我尝试返回 temp [] 时,它给了我一个错误。不太确定会发生什么让它做到这一点。

class' expected
      return temp[];
4

3 回答 3

1

代码错误:你有一个

Letter temp = new Letter ...

重命名它。

也改变

return temp[];

return temp;

设计错误:使用ArrayList<Letter>而不是数组。它有add方法。http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

于 2013-11-23T20:39:46.977 回答
0

引用变量时不需要方括号。只有在声明变量类型以及在特定索引处设置/获取值时才需要它。

所以而不是:

return temp[];

采用:

return temp;

此外,我从您的代码中看到另一个错误:

Letter temp = new Letter(toName, toAddress, toCity, toState, toZip, fromName, fromAddress, fromCity, fromState, fromZip, weight);

int x = array.length - 1;
temp[x] = temp;

该变量temp被用作数组和单个变量。选择一个不同的名称。

于 2013-11-23T20:40:06.960 回答
0

正确的代码

public class Letter {

    public static Letter[] addLetter(Letter[] array, Scanner kb) {
        Letter[] temp = new Letter[array.length + 1];

        // ....

        Letter tempItem = new Letter(toName, toAddress, toCity, toState, toZip, fromName, fromAddress, fromCity, fromState, fromZip, weight);
        int x = array.length - 1;
        temp[x] = tempItem;

        return temp;
    }
}
于 2013-11-23T20:40:43.540 回答