I am creating an object orientated mastermind game. I have all the classes and methods set-up and have tried them in a non object orientated programming style and they all work but now since I have them in object orientated style I get the null pointer error. It tells me where the error is occurring and I have tried to figure out what is the null value or what is wrong but I cannot figure it out. I have also tried taking out the point where the null happens just to get another null exception at a similar type expression. So I believe that I have the syntax wrong for invoking methods or such but do not know how to fix it or if it’s the cause of the real error.
The second code block is where the error occurs if you want to jump straight to it.
I know I’ve posted a lot of stuff here so if you need any clarification I’ll gladly help. The main focus is just the null error so if there is some other error that you see just ignore it unless it impedes on solving the null error.
I separated each class for easier reading.
public class GameTester {
public static void main(String[] args) {
MasterMind m = new MasterMind();
m.playGame();
}
}
public class MasterMind
{
private Master theMaster;
private Player thePlayer;
public void mastermind() {
theMaster = new Master();
thePlayer = new Player();
}
public void playGame() {
System.out.println("WELCOME TO CODEBREAKER... Let's Play!\n");
System.out.println("Guess a 4-letter code with letters A, B, C, and D\n");
theMaster.createCode(); //heres where the null exception is said to occur
while(true) {
thePlayer.makeGuess(); //if i remove the call above this becomes null error
int x = theMaster.totalCorrect(thePlayer.getGuess());
if( x == 4) {
System.out.println("\nGOT IT!!!\n");
}
else {
System.out.printf("MISSED! %d out of 4. TRY AGAIN... \n", x);
}
}
}
import java.util.Random;
public class Master
{
private char[] Code = new char[4];
public Master()
{
}
public void createCode()
{
Random R = new Random();
char[] setting ={'A', 'B', 'C', 'D'};
int rx;
for(int i=0; i<=3; i++)
{
rx = R.nextInt(4);
Code[i] = setting[rx];
}
}
public int totalCorrect(char[] theGuess)
{
int x =0;
if(Code[0] == theGuess[0]) {
x++;
}
if(Code[1] == theGuess[1]) {
x++;
}
if(Code[2] == theGuess[2]) {
x++;
}
if(Code[3] == theGuess[3]) {
x++;
}
return x;
}
}
import java.util.Scanner;
public class Player {
private char[] Guess = new char[4];
public Player() {
}
public void makeGuess() {
System.out.println("YOUR GUESS => ");
Scanner input =new Scanner(System.in);
String guess = input.next();
char[] D = guess.toCharArray();
for(int i=0; i<4; i++) {
Guess[i] = D[i];
}
}
public char[] getGuess() {
return Guess;
}
}
Using final on attribute declaration you enforce the life-cycle of the instances, and you don’t need a constructor: