Hangman game errors - java

Here is my program so far:
import java.util.Arrays;
public class HangmanWord {
private String[] possibleWords = {"laptop", "college", "programing"};
private String word;
private char[] progress;
private int wrongCount = 0;
public HangmanWord() {
int randomPossibleWord = (int) (Math.random() * possibleWords.length-1);
String word = possibleWords[randomPossibleWord];
char[] progress = new char[word.length()];
Arrays.fill(progress,'-');
}
public void display() {
System.out.print(progress);
System.out.println();
}
public boolean guess(char c) {
boolean matchFound = false;
for (int i = 0; i < word.length(); i++ ) {
if (word.charAt(i) == c ) {
progress[i] = c;
matchFound = true;
}
}
return false;
}
public boolean isSolved() {
for (int i = 0; i < progress.length; i++ ) {
if(progress[i] == '-'){
return false;
}
}
return true;
}
public int getWrongCount() {
return wrongCount;
}
public String getWord() {
return word;
}
}
public class Hangman {
public static void main(String[] args) {
int MAX_INCORRECT = 5;
System.out.println("Welcome to Hangman.");
HangmanWord wordObj = new HangmanWord();
System.out.print("Here is your word: ");
wordObj.display();
}
}
My output should look something like this:
Welcome to Hangman.
Here is your word: ------
However, I am getting the following errors:
Welcome to Hangman.
Here is your word: Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Writer.java:127)
at java.io.PrintStream.write(PrintStream.java:503)
at java.io.PrintStream.print(PrintStream.java:653)
at HangmanWord.display(HangmanWord.java:16)
at Hangman.main(Hangman.java:9)

You are redefining the variable word and progress in your constructor. You should simply use them without declaring them as a new variables because they're already defined. Currently you are defining them locally, the constructor works but uses those local defined variables and not your object's word and progress variables, therefore when you leave scope and call display() it will use your object's progress array which was never actually initialized.
Change it to the following so you aren't redefining the variables word and progress like so
public HangmanWord() {
int randomPossibleWord = (int) (Math.random() * possibleWords.length-1);
word = possibleWords[randomPossibleWord];
progress = new char[word.length()];
Arrays.fill(progress,'-');
}

Related

Finite State Machine Program invalid output

I am working on a project and my code isn't working not sure why. Given the test program and general class I need a program that satisfies the following logical regular epxression:
L1: For alphabet {a,b}, all strings that contain an odd number of a's and exactly one b.
Test input: aabaaaa, aaabaaaa, aabaaaab, baaaaaa, aaaaabaa
What it should be:
aabaaaa False
aaabaaaa True
aabaaaab false
baaaaaa false
aaaaabaa True
Program output:
(ture, true, true, false, true)
My Test program:
import java.util.Scanner;
// Test Finite State Machine Class
public class TestFSML1
{
public static void main(String[] args){
String A = "ab";
int[][] ST = {{1,3,0},
{1,2,1},
{2,2,2},
{3,3,3}};
int[] AS = {0,0,1,0};
Scanner in = new Scanner(System.in);
String inString;
boolean accept1 = false;
FSM FSM1 = new FSM(A, ST, AS);
// Input string is command line parameter
System.out.println(" Input Accepted:");
for(int i=0;i<args.length;i++) {
inString = args[i];
accept1 = FSM1.validString(inString);
System.out.printf("%10s%13s\n",inString, accept1);
}
} // end main
} // end class
FSM Class
// Finite State Machine Class
public class FSM
{
// Instance variables
public String alphabet;
public int stateTrans[][];
public int acceptState[];
private int cstate;
// Constructor function
public FSM(String A, int[][] ST, int[] AS)
{
int NSYMBOLS = A.length();
int NSTATES = AS.length;
// Alphabet
alphabet = "" + A;
// State transition table
stateTrans = new int[NSTATES][NSYMBOLS];
for(int r = 0; r < NSTATES; r++)
for(int c = 0; c < NSYMBOLS; c++)
stateTrans[r][c] = ST[r][c];
// Accept states
acceptState = new int[NSTATES];
for(int r = 0; r < NSTATES; r++)
acceptState[r] = AS[r];
// Start state
cstate = 0;
}
// Methods
public int getState()
{
return cstate;
}
public void setState(int state)
{
cstate = state;
return;
}
public int nextState(char symbol)
{
int nstate = -1;
int col = alphabet.indexOf(symbol);
if(col >= 0)
nstate = stateTrans[cstate][col];
return nstate;
}
public boolean accept(int state)
{
if(state < 0)
return false;
return (acceptState[state] != 0);
}
public boolean validString(String word)
{
cstate = 0;
for(int k = 0; k < word.length(); k++){
cstate = nextState(word.charAt(k));
System.out.print(cstate);
System.out.println(" " + word.charAt(k));
if(cstate < 0)
return false;
}
return accept(cstate);
}
} // end class
Thanks!
Here's a simple method I typed up to perform the task you wanted.
public static boolean validWord(String s) {
int aCounter = 0;
int bCounter = 0;
char c;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if ((int) c == (int) 'a') {
aCounter++;
} else {
bCounter++;
}
}
return (aCounter % 2 == 1 && bCounter == 1);
}
I had trouble understanding how you were implementing your method, and I think it could be much simpler. I'm sure the instance variables you included in the FSM class serve some other use, but I you don't really need any of them to analyze the string. Just use something like this, it should be easy enough to integrate into your code as all it takes is the string. Hope this helps!

whenever try to push onto stack gives error in java null pointer exception

In this code as user enters string it is pushed onto stack and if "-" appears then previous string is popped out and when the stack becomes empty then loop execution stops.
Whenever I try to push onto stack null pointer exception is there.
import java.util.Scanner;
import java.util.*;
public class StackArray {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
StackArrayModel stack = new StackArrayModel();
while (true) {
String data = scan.next();
if (data.equals("-")) {
if (stack.isEmpty() == false)
System.out.println(stack.pop());
else
break;
} else {
stack.push(data);
}
}
}
}
// creating resizable array stack
class StackArrayModel {
String[] s;
int n = 0;
public void StackArrayModel() {
s = new String[1];
}
public boolean isEmpty() {
return n == 0;
}
public void push(String item) {
if (n == s.length) {
resize(s.length * 2);
}
s[n++] = item;
}
private void resize(int capacity) {
String[] copy = new String[capacity];
for (int i = 0; i < s.length; i++) {
copy[i] = s[i];
}
s = copy;
}
public String pop() {
if (n > 0 && n == s.length / 4)
resize(s.length / 2);
String item = s[--n];
s[n] = null;
return item;
}
}
The error is in StackArrayModel class. You didn't overwrite the default constructor, because you added a void there.
public void StackArrayModel(){
s = new String[1] ;
}
should be changed to following so it overwrites the default constructor:
public StackArrayModel(){
s = new String[1] ;
}
Once you did that, you've overwritten the default constructor, and your code should work just fine.

boolean method in arrays of type class

I have trouble to compile this method. This method is to search in the array of type Event. So say if the month contains [1,2,3,4,5,6,7*,8,9*], it will search the ones with asterisks and return true
public static boolean isSignificant(Event[] month, String SearchValue)
{
boolean isFound = false;
for(int i = 0; i< month.length && isFound == false; i++)
{
if(month[i].contains(SearchValue)) // error on this line
{
isFound = true;
}
}
return isFound;
}
There are many ways to search this pattern
if (value.endsWith("*")) {
if (value.matches(".*\\*$")) {
value.matches(".*?\\*$")
e.g.
public class HelloWorld
{
static String[] month = new String[]{"1","2","3","4","5","6","7*","8","9*"};
public static boolean isSignificant()
{
boolean isFound = false;
for(int i=0; i <month.length && isFound == false; i++)
{
if(month[i].endsWith("*"))
{
isFound = true;
}
}
return isFound;
}
public static void main(String []args)
{
HelloWorld obj = new HelloWorld();
if(obj.isSignificant())
{
System.out.println("The string ends with *");
}
else
{
System.out.println("The string donot end with *");
}
}
}
#Jean-François Savard is right, month is of type Event while you are searching for a String. If you explain to me with more info i could help you more, otherwise ill just assume you mean a string array.
public class HelloWorld{
public static void main(String []args){
System.out.println("Hello World");
String [] array = {"1","2","3","4*"} ;
if(isSignificant(array,"*")){
System.out.println("Found");
}else{
System.out.println("Not found");
}
}
public static boolean isSignificant(String[] month, String SearchValue) {
for(int i = 0; i< month.length; i++) {
if(month[i].contains(SearchValue)) {
return true;
}
}
return false;
}
}

implementing a method from one class to another?

I am making a program for airplane seating arrangements for a class and i ended up making two toString methods but when I run the program the toString method in my airplane class is making something not work specifically:
str= str + seats[i][j].toString();
I believe that simply deleting the toString method in the seat class and somehow putting it back into the airplane class toString method would fix the problem or make it simpler. What's wrong?
Airplane class:
public class Airplane
{
private Seat [ ] [ ] seats;
public static final int FIRST_CLASS = 1;
public static final int ECONOMY = 2;
private static final int FC_ROWS = 5;
private static final int FC_COLS = 4;
private static final int ECONOMY_ROWS = 5;
private static final int ECONOMY_COLS = 6;
public Airplane()
{
seats = new Seat[FC_ROWS][ECONOMY_COLS];
}
public String toString()
{
String str = "";
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
str= str + seats[i][j].toString();
}
str = str + "\n";
}
return str;
}
}
Seat Class:
public class Seat
{
private int seatType;
private boolean isReserved;
public static final int WINDOW = 1;
public static final int AISLE = 2;
public static final int CENTER = 3;
public Seat(int inSeatType)
{
seatType = inSeatType;
isReserved = false;
}
public int getSeatType()
{
return seatType;
}
public void reserveSeat()
{
isReserved = true;
}
public boolean isAvailable()
{
if (!isReserved)
{
return true;
}
else return false;
}
public String toString()
{
if(isReserved == false)
{
return "*";
}
else return "";
}
}
In Seat.toString you should print a " " not "".
You're array is FC_ROWS by ECONOMY_COLS, so you're not creating all the seats. You should probably have two arrays (one for FC, one for Economy), since FC_ROWS != ECONOMY_ROWS.
You aren't actually creating Seats in your constructor. Use a nested loop to create them, otherwise you will get a NullPointerException. Creating an array doesn't create the objects contained in the array.
When you're creating the seats in the Airplane constructor, use if statements to figure out if the seat is supposed to be a Window, Aisle, etc.
seats seems to does not have Seat's instance.
Add this code :
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
seats[i][j] = new Seat();
}
}
below this :
seats = new Seat[FC_ROWS][ECONOMY_COLS];
I think that in Seat::toString, you mean to return " " (a space) if it isn't reserved.

Null pointer exception for Array of Objects

I am new to using arrays of objects but can't figure out what I am doing wrong and why I keep getting a Null pointer exception. I am trying to create an Theatre class with an array of spotlight objects that are either set to on or off. But - whenever I call on this array I get a null pointer exception.
package theatreLights;
public class TheatreSpotlightApp {
public static void main(String[] args) {
Theatre theTheatre = new Theatre(8);
System.out.println("element 5 " + theTheatre.arrayOfSpotlights[5].toString());
}
}
package theatreLights;
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i].turnOn();
}
}
}
package theatreLights;
public class spotlight {
int state;
public spotlight(){
state = 0;
}
public void turnOn(){
state = 1;
}
void turnOff(){
state = 0;
}
public String toString(){
String stringState = "";
if(state == 0){
stringState = "is off";
}
else if(state==1){
stringState = "is on";
}
return stringState;
}
}
I must be doing something basic wrong in creating the array but can't figure it out.
replace
arrayOfSpotlights[i].turnOn();
with
arrayOfSpotLights[i] = new Spotlight();
arrayOfSpotlights[i].turnOn();
The line
arrayOfSpotlights = new spotlight[N];
will create an array of spotlights. It will however not populate this array with spotlights.
When you do "arrayOfSpotlights = new spotlight[N];" you init an array of length N, what you need to do is also init each object in it:
for i=0; i<N; i++
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
Hope I'm correct :)
You are not creating an spotlight objects.
arrayOfSpotlights = new spotlight[N];
This just creates an array of references to spotlights, not the objects which are referenced.
The simple solution is
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
}
BTW You should use TitleCase for class names.
You could write your class like this, without using cryptic code like 0 and 1
public class Spotlight {
private String state;
public Spotlight() {
turnOff();
}
public void turnOn() {
state = "on";
}
void turnOff() {
state = "off";
}
public String toString() {
return "is " + state;
}
}
You declared the array arrayOfSpotlights, but didn't initialize the members of the array (so they are null - and you get the exception).
Change it to:
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i]=new spotlight();
arrayOfSpotlights[i].turnOn();
}
}
}
and it should work.

Categories