Java构造函数找不到符号错误'= new'

时间:2014-11-26 00:36:54

标签: java constructor cannot-find-symbol

我试图在另一个类的条件中初始化一个Java类 - 我希望MarsRovers初始化Rover。我找不到符号'我尝试从MarsRovers初始化Rover对象时出错。我是Java的新手,所以我觉得它与plateauCoords和inputLines的范围有关。我已经尝试过我在这里看过的其他解决方案,但他们并没有为我的问题工作(比如公开我的变量)。

只要inputLines%2等于0(使用until循环),目标是最终创建一个新的Rover。

这是MarsRover代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class MarsRover {
  public static void main(String []args) throws FileNotFoundException {
    Scanner console = new Scanner(System.in);
    System.out.println("Mars rover is ready for input, please enter name of input file: ");
    String filename = console.nextLine();
    console.close();
    List<String> inputLines = new ArrayList<String>();

    Scanner scanner = new Scanner(new File(filename));
    scanner.useDelimiter("\n");
    while(scanner.hasNext()){
      inputLines.add(scanner.next());
    }
    String plateauCoords = inputLines.get(0);
    inputLines.remove(0);
    scanner.close();
    System.out.println(inputLines);

    if(inputLines.size() % 2 == 0) {
      MarsRover rover = new Rover(plateauCoords, inputLines);
    } else {
      System.out.println("Your directions are not formatted correctly");
    }
  }
}

这是罗孚代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class Rover {
  public Rover(String platCoords, String[] input) {
    System.out.println("INSIDE ROVER");
  }
}

当我编译MarsRovers.java时,我收到此错误:

MarsRover.java:27: cannot find symbol
symbol  : constructor Rover(java.lang.String,java.util.List<java.lang.String>)
location: class Rover
      MarsRover rover = new Rover(plateauCoords, inputLines);
                        ^
1 error

2 个答案:

答案 0 :(得分:1)

List<String>的类型无法分配给String[],因此类型检查失败。

前者是List(实际上运行时类型较窄,因为List只是interfaceString的通用实例,而后者是String的数组{1}}对象。

您应该将List<String>转换为数组。 JDK已经提供了这个功能:

String[] array = inputLines.toArray(new String[inputLines.size()]);

答案 1 :(得分:1)

您定义的Rover构造函数需要一个字符串数组。您正尝试使用字符串列表调用构造函数。字符串列表与字符串数组不同。您可以通过将列表转换为字符串数组来修复它。

Rover rover = new Rover(plateauCoords, inputLines.toArray(new String[inputLines.size()]));

另外请注意,您不能将Rover类型的对象分配给MarsRover类型的变量,因为(如定义的)它们是完全不同的类型。

相关问题