我的代码有问题。
线程“ main”中的异常java.lang.NullPointerException
我已附加了游戏Java代码。 我知道我需要在Game.getHiddenMovieTitle下进行更改 我试图更改Game.getHiddenMovieTitle的一些代码。
import javax.swing.*;
import java.util.Scanner;
public class Main {
public static void main(String [] args){
Game game = new Game("file.txt");
System.out.println("Let play a mind guess game.");
System.out.println("Welcome to Guess the Movie!");
System.out.println("The rules are simple, the computer randomly picks a movie title, and shows you how many letters it's made up of.");
System.out.println("If you lose 10 points, game over!");
System.out.println("Let's start!");
while (!game.gameEnd()){
System.out.println("You are guessing:" + game.getHiddenMovieTitle());
System.out.println("You have guessed (" + game.getWrongletter().length()/2 + ") wrong letters:" + game.getWrongletter());
game.guessLetter();
}
if(game.getWon()){
System.out.println("You win!");
System.out.println("You have guessed " + game.getMovieTitle() + " correctly.");
}
else{
System.out.println("You have guessed (" + game.getWrongletter().length()/2 + ") wrong letters:" + game.getWrongletter());
System.out.println("You lost!");
System.out.println("The movie title was " + game.getMovieTitle());
System.out.println("Better luck next time.");
}
}
}
import java.util.Scanner;
public class Game {
private String movieGuess;
private int points;
private String wrongl;
private String rightl;
private boolean won;
public Game(String path) {
MovieList movieList = new MovieList(path);
movieGuess = movieList.getRandomMovie();
points = 0;
wrongl = "";
rightl = "";
won = false;
}
public String getMovieTitle(){
return movieGuess;
}
public String getHiddenMovieTitle() {
if(rightl.equals("")){
return movieGuess.replaceAll("[a-zA-Z]", "_");
}
else{
return movieGuess.replaceAll("[a-zA-Z&&[^" + rightl +"]]", "_");
}
}
public String getWrongletter(){
return wrongl;
}
public boolean getWon(){
return won;
}
public boolean gameEnd(){
if (points >= 10){
return true;
}
getHiddenMovieTitle();
return false;
}
private String inputLetter(){
System.out.println("Guess a letter");
Scanner scanner = new Scanner(System.in);
String letter = scanner.nextLine().toLowerCase();
if(!letter.matches("[a-z]")){
System.out.println("That is not a letter. Please enter a letter not a number.");
}
else if(wrongl.contains(letter) || rightl.contains(letter)){
System.out.println("You have already guess that letter.");
}
else{
return letter;
}
return letter;
}
void guessLetter(){
String guessedLetter = inputLetter();
if(movieGuess.toLowerCase().contains(guessedLetter)){
rightl += guessedLetter + guessedLetter.toUpperCase();
}
else{
wrongl += "" + guessedLetter;
}
}
}