【发布时间】:2019-05-06 17:16:17
【问题描述】:
我正在猜测我从文本文件中获取电影列表的电影游戏。我有两个课程 Game 用于获取随机电影,Main 用于游戏的其余部分。现在我想通过更改Game 中的文本文件来添加好莱坞或宝莱坞电影的选择。我分别将“h”或“b”作为输入。我用参数调用Game 的构造函数以相应地选择文件,但它不起作用,并且文件总是null 并显示NullPointerException。
编辑:我是 OOP 的新手,所以请多多包涵。我刚刚在调试过程中看到调试器首先进入类字段,然后进入构造函数,我实际上试图使用file(在构造函数内部)来初始化其他字段,因为它的值是@987654330 @ 并显示 NullPointerException。
现在我的问题仍然是如何使用file 和noOfMovies 来初始化Game 中的其他字段。
//showing the setter method that i tried
//Main class
/*only showing the part having Game class*/
//making an object of Game class to get a random movie from the file
System.out.println("Enter 'h' for hollywood and 'b' for bollywood ");
Scanner input = new Scanner(System.in);
char genre = input.next().charAt(0);
Game newGame = new Game(genre);
//Game class
public class Game
{
public Game(char genre)
{
setMovieList(genre);
}
File file;
int noOfMovies;
public void setMovieList(char genre)
{
if(genre == 'h')
{
this.file = new File("C:\\Users\\Rashim\\Desktop\\java\\GuessTheMovie\\src\\hollywoodMovies.txt");
this.noOfMovies = 30;
}
else if(genre == 'b')
{
this.file = new File("C:\\Users\\Rashim\\Desktop\\java\\GuessTheMovie\\src\\bollywoodMovies.txt");
this.noOfMovies = 20;
}
// EDIT ------> I want to initialize the below fields <-------
private Scanner scan = new Scanner(this.file);
private int lineCount = 0;
int random = (int)(Math.random()*noOfMovies)+1;
//array for storing the movie titles
private String[] movieArray = new String[noOfMovies];
}
【问题讨论】:
-
在另外两个
if之后添加一个带有消息的 else 块 - 所以你知道正在传递什么:} else { System.out.println("unrecognized genre: " + genre); }或抛出异常:} else { throw new IllegalArgumentException("invalid genre: " + genre); }{{可能错误是你如何正在确定该文件为空,我们看不到该部分}} -
请使用调试器找出实际发生的情况。一个常见的问题可能是当您实际运行代码时,
src目录不可用,或者路径拼写错误。打开文件前打印路径,并使用shell检查文件是否存在。 -
@CarlosHeuberger 我知道它看起来很傻,但我觉得它永远不会进入构造函数,并且 setMovieList 永远不会因为我使用调试器而被调用,它永远不会在构造函数内或 setMovieList 上停止。它总是跳过它并使用初始值。
-
then 或者第一个发布的部分没有被执行,或者有另一个
Game类(另一个包,或者没有编译的实际版本)。在带有new Game的语句处停止调试器并查看它跳转到的位置{{只需确认您的构造函数没有像public void Game(char genre)那样声明 - 一个简单的方法,而不是构造函数} -
您在此处发布的代码看起来不错...它按预期工作,它进入构造函数并正确调用 setMovieList...您确定您正在执行此代码吗?
标签: java oop constructor