Nullpoint exeption
Hello. I磎 trying to make an HangMan game. I think I磎 close to done but I got som issue left. When I run the program I磎 recivning "Nullpointer exception" into this class who is supposed to make all calculations:
publicclass ModellKlass{
privatechar[] secretWord;// secret word
private String word;// secret word in a string
privatechar[] status;// the correct guesses
private String wrong;// all wrong guesses
public ModellKlass(String word){
secretWord =newchar[word.length()];
// ******* This for sats is giving me the error. Any idea whats wrong? ********
for(int i=0; i < word.length(); i++){
secretWord[i] = word.charAt(i);
}
status =newchar[word.length()];
}
// Take guesses
publicvoid guess(char c){
for(int i=0; i < word.length(); i++){
if(secretWord[i] == c){
// Contains all correct guesses
status[i] = c;
}
else wrong = wrong + c;
}
}
// Return a string for the user with correct guesses
public String showWord(){
String correct ="";
for(int i=0; i < status.length; i++){
correct = correct +" " + status[i];// String+Int OK ?
}
return correct;
}
// Return number of wrong guesses
publicint getErrors(){
int nrOfWrong = wrong.length();
return nrOfWrong;
}
}
There we got the view class and I磎 not sure if I can make that "switch" bether? Now I磎 rewriting everything over and over again. Would be a lot bether I could reuse the old lines somehow:
import javax.swing.*;
import java.awt.*;
publicclass VyKlassextends JPanel{
private ModellKlass mod;
public VyKlass(ModellKlass model){
mod = model;
}
publicvoid paintComponent(Graphics g){
g.clearRect(0,0,getWidth(),getHeight());
int errors = mod.getErrors();
// draws up the gallion(part of it) when number of wrong answers(error) == int x
switch (errors){
case 0: g.drawLine(0,0,0,0);
case 1: g.drawLine(10,60,0,50);break;
case 2: g.drawLine(10,60,0,50);
g.drawLine(10,10,30,0);break;
case 3: g.drawLine(10,60,0,50);
g.drawLine(10,10,30,0);
g.drawLine(40,30,0,20);break;
}
//Draws a test string into the JFrame and the number of wrong answers
g.drawString("test",20,100);//mod.showWord(),20,100);
g.drawString((String)""+mod.getErrors(),20,120);
}
publicvoid run(char c){
mod.guess(c);
repaint();
}
}
and at last my main class I磎 not sure of eighter. First time I make an console/inputer thing in it. Is "nextLine" the correct method to use when reciving the line?
import javax.swing.*;
import java.util.*;
publicclass Main{
publicstaticvoid main(String[] args){
JFrame frame =new JFrame("HangMan");
frame.setSize(400,400);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
ModellKlass mod =new ModellKlass("test");
VyKlass vy =new VyKlass(mod);
frame.add(vy);
frame.setVisible(true);
// adding an input for the guesses
Scanner ch =new Scanner(System.in);
while (true)
{
System.out.println("Guess: ");
String c = ch.nextLine();
// converting the string into a char and sending it to the "run" method in vy
vy.run(c.charAt(0));
}
}
}
Big thanks in advance!
Message was edited by:
Hunter78

