返回一个数组,但给出.class java

时间:2013-11-23 20:36:41

标签: java java.lang.class

嘿伙计们,我是一名新手程序员,我从这里得到一个.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[];

3 个答案:

答案 0 :(得分:1)

代码错误:你有一个

Letter temp = new Letter ...

重命名。

同时更改

return temp[];

return temp;

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

答案 1 :(得分: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既用作数组又用作单个变量。选择其他名称。

答案 2 :(得分: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;
    }
}