Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hELLO GUYZ PLEASE HELP ME I AM MAKING A HANGMAN GAME THIS IS MY SCHOOL PROJECT AND I HAVE TO SUMBIT IT TOMMOROW AND I AM GETTING A ERROR IN MY CODE
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at HangmanGameFrame.<init>(HangmanGameFrame.java:24)
at HangmanGameFrame$5.run(HangmanGameFrame.java:447)

What I have tried:

HERE IS MY CODE


import java.io.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

/**
*
* @author Muhammmad Kashif
*/
public class HangmanGameFrame extends javax.swing.JFrame {
char c;
String pass;
String[] words=readArray("words.txt");
Random rn=new Random();
int randomNumber = rn.nextInt(words.length);
String answer;
int numberofMisses=0;
String rightorWrong;
ArrayList<string> letterArrayList=new ArrayList<>();
int numberofBlank;
ImageIcon hang=new ImageIcon("First.png");
ImageIcon hang1=new ImageIcon("Second.png");
ImageIcon hang2=new ImageIcon("Third.png");
ImageIcon hang3=new ImageIcon("Fourth.png");
ImageIcon hang4=new ImageIcon("Fifth.png");
ImageIcon hangdead=new ImageIcon("First.png");
public HangmanGameFrame() {
initComponents();
getContentPane().setBackground(Color.WHITE);
wrongwords.setText(null);
answer = words[randomNumber];
answer = answer.toUpperCase();

StringBuilder tempDisplayAnswer= new StringBuilder(answer);
for(int x=0; x<=answer.length()-1;x++)
{
tempDisplayAnswer.setCharAt(x,'-');
String displayAnswer=tempDisplayAnswer.toString();
labelword.setText(displayAnswer);
}
hangman.setIcon(hang);
exit.setVisible(false);
Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.size().width/2,dim.height/2-this.getSize().height/2);
}



/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

conform = new java.awt.Button();
exit = new javax.swing.JButton();
hangman = new javax.swing.JLabel();
labelword = new javax.swing.JLabel();
inputtext = new javax.swing.JTextField();
outputtext = new javax.swing.JTextField();
infoNOofMisses = new javax.swing.JLabel();
labOutputNoOfMisses = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
wrongwords = new javax.swing.JTextArea();
tryagain1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

conform.setLabel("CONFORM!");
conform.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
conformActionPerformed(evt);
}
});

exit.setText("EXIT");
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});

labelword.setFont(new java.awt.Font("Tahoma", 1, 60)); // NOI18N
labelword.setText("- - - ");

inputtext.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
inputtextKeyTyped(evt);
}
});

infoNOofMisses.setText("No. Of Misses:");

wrongwords.setColumns(20);
wrongwords.setRows(5);
jScrollPane1.setViewportView(wrongwords);

tryagain1.setText("TRY AGAIN!");
tryagain1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tryagain1ActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(32, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(infoNOofMisses, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(labOutputNoOfMisses, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51)
.addComponent(labelword)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hangman, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(221, 221, 221))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(conform, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(101, 101, 101)
.addComponent(exit, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(59, 59, 59))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(157, 157, 157)
.addComponent(inputtext, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(tryagain1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40))))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(outputtext, javax.swing.GroupLayout.PREFERRED_SIZE, 628, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(hangman, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(58, 58, 58)
.addComponent(tryagain1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(39, 39, 39))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(labOutputNoOfMisses, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(77, 77, 77)
.addComponent(labelword, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(infoNOofMisses, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addGap(18, 18, 18)
.addComponent(inputtext, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(133, 133, 133)))
.addComponent(outputtext, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(conform, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(exit, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)))
);

pack();
}//
public static String[] readArray(String file){
//step 1: Count How many Lines
// Step2: Create array and copy the elements in.
int ctr=0;
try{
Scanner s1=new Scanner(new File(file));
while(s1.hasNextLine())
{
ctr=ctr+1;
s1.next();
}
String[] words=new String[ctr];
Scanner s2=new Scanner(new File(file));
for(int i=0;i<ctr;i++)
{
words[i]=s2.next();
}
return words;
}
catch(FileNotFoundException e)
{

return null;}
}
static public int SortedLinearSearch(String [] A,String B)
{
for(int k=0;k<A.length;k++)
{
if(A[k].equals(B))
{
return k;
}
}
return -1;
}
private void exitActionPerformed(java.awt.event.ActionEvent evt) {
HangmanGameFrame.this.dispose();
}

private void conformActionPerformed(java.awt.event.ActionEvent evt) {
numberofBlank=(labelword.getText()).length();
String b=inputtext.getText();
for(int x=0;x<=answer.length()-1;x++){ //add char of the answer to "LetterArrayList"
letterArrayList.add(String.valueOf(answer.charAt(x)));
}
String[] letter=new String[answer.length()];
for(int x=0;x<answer.length()-1;x++) // Convert Array List To Array
{
letter[x]=letterArrayList.get(x);
}
if(numberofMisses<6)// error trapping for blank inputbox
{
if(wrongwords.getText().equals("")){
pass="yes";
}
else{
pass="no";
}
if(inputtext.getText().equals(""))
{
outputtext.setText("Please Give Me A Letter! ");
}
if(!inputtext.getText().equals("")){
for(int x=0;x<=(wrongwords.getText()).length()-1;x++)
{
char WrongLetter=(wrongwords.getText()).charAt(x); //determine wheather key is repeated or not
if((inputtext.getText()).charAt(0) != WrongLetter){
pass="yes";
}
else if((inputtext.getText()).charAt(0)== WrongLetter){
pass="no";
outputtext.setText("This Letter Is Already Used");
break;
}
}}

if(pass=="YES"){
if(Character.isLetter(c)){
if(SortedLinearSearch(letter,b)== -1){
wrongwords.setText(wrongwords.getText()+String.valueOf(inputtext.getText())+" ");
//For Audios
InputStream in;
try{
in=new FileInputStream(new File(""));
AudioStream audios=new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
///////////

for(int x=0;x<wrongwords.getText().length()-1;x++)
{
if(Character.isLetter((wrongwords.getText()).charAt(x))){
numberofMisses++;
break;
}
}
}
}
}
inputtext.setText(null);
}
//change image of Hangman
if(numberofMisses==1)
{
hangman.setIcon(hang);
}
else if(numberofMisses==2)
{
hangman.setIcon(hang1);
}
else if(numberofMisses==3)
{
hangman.setIcon(hang2);
}
else if(numberofMisses==4)
{
hangman.setIcon(hang3);
}
else if(numberofMisses==5)
{
hangman.setIcon(hang4);
}

if(numberofMisses == 6) //loosing condition
{
hangman.setIcon(hangdead);
outputtext.setText("You Lost !");
inputtext.setEnabled(false);
conform.setEnabled(false);
exit.setEnabled(true);
////// AUDIO
InputStream in;
try{
in=new FileInputStream(new File(""));
AudioStream audios=new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch (Exception e){
JOptionPane.showMessageDialog(null,e);

}
////////////////////////////////////////////////////////////////
}

if(SortedLinearSearch(letter,b)!=-1){
StringBuilder tempWord=new StringBuilder(labelword.getText());
tempWord.setCharAt(SortedLinearSearch(letter,b),letter[SortedLinearSearch(letter,b)].charAt(0));
String displayAnswer=tempWord.toString();
labelword.setText(displayAnswer);
//////audio
InputStream in;
try{
in=new FileInputStream(new File(""));
AudioStream audios=new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch (Exception e){
JOptionPane.showMessageDialog(null,e);
}
///////////////////////////////////
}
for(int x=0;x<=labelword.getText().length()-1;x++)
{
if(((labelword.getText()).charAt(x)) != '-'){
numberofBlank--; //count number Of blanks in labelword
}
}
if(numberofBlank ==0){
conform.setEnabled(false);//if no label - player wins
outputtext.setText("Hurray! You Won");
exit.setVisible(true);
InputStream in;
try{
in=new FileInputStream(new File(""));
AudioStream audios=new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch (Exception e){
JOptionPane.showMessageDialog(null,e);
}
///////////////////////////
}
labOutputNoOfMisses.setText(String.valueOf(numberofMisses));
}

private void inputtextKeyTyped(java.awt.event.KeyEvent evt) {
if(numberofMisses<6){
c=evt.getKeyChar();
if(!(Character.isLetter(c))){
outputtext.setText("A Letter Please");
evt.consume();
inputtext.setText("");

}
else{
if(inputtext.getText()!=null){
inputtext.setText(null);
outputtext.setText("");
}
if(Character.isLowerCase(c)){
evt.setKeyChar(Character.toUpperCase(c));
}}
}
}

private void tryagain1ActionPerformed(java.awt.event.ActionEvent evt) {
this.setVisible(false);
new HangmanGameFrame().setVisible(true); //this will refresh page
///////////audio
InputStream in;
try{
in=new FileInputStream(new File(""));
AudioStream audios=new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch (Exception e){
JOptionPane.showMessageDialog(null,e);

}
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(HangmanGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HangmanGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HangmanGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HangmanGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new HangmanGameFrame().setVisible(true);
}
});
}

// Variables declaration - do not modify
private java.awt.Button conform;
private javax.swing.JButton exit;
private javax.swing.JLabel hangman;
private javax.swing.JLabel infoNOofMisses;
private javax.swing.JTextField inputtext;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labOutputNoOfMisses;
private javax.swing.JLabel labelword;
private javax.swing.JTextField outputtext;
private javax.swing.JButton tryagain1;
private javax.swing.JTextArea wrongwords;
// End of variables declaration
static class setVisible{
public setVisible(boolean b){

}
}
}
Posted
Updated 23-Mar-18 8:51am

1 solution

As far as I can see, line 24 is:
int randomNumber = rn.nextInt(words.length);

That would suggest that words is null. Which means that readArray("words.txt") didn't return anything.

Looking at the code for readArray, that would suggest you're getting a FileNotFoundException, which means the file doesn't exist.

But you could have found that out for yourself, if only you'd used the debugger!
 
Share this answer
 
Comments
Member 13743392 23-Mar-18 16:30pm    
I have tried each and every thing but cant get over this error i have even removed this lines of code readArray But Still The same Error Occures.
Richard Deeming 23-Mar-18 16:35pm    
If you removed the line completely, then you wouldn't have declared the variable, so you'd get a compiler error.

If you removed the call to readArray, and set the variable to null, then you're obviously going to get a NullPointerException when you try to access one of its properties.

The solution is to fix the FileNotFoundException, by making sure the file exists.
Member 13743392 23-Mar-18 16:38pm    
can you help me out that how can i readArray from a file how to take the words in the file i have taken like this
FAT
EGG
POSTER
MACHINE
Member 13743392 23-Mar-18 16:39pm    
Please Can you rewrite the errored line by correcting it that might be helpfull for me!
Richard Deeming 23-Mar-18 16:41pm    
As I keep telling you, the only way to correct it is to make sure the file "words.txt" exists in the path you're trying to read it from.

I can't do that for you, because I don't have access to your computer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900