# Rhino's "I need Java help" thread



## Easy Rhino (Sep 10, 2009)

hey guys and gals, i am trying to write a java problem that accomplishes a fairly simple task. the program asks if a student would like to solve an addition problem or a subtraction problem. the problem generates 2 random numbers. whichever option the user chooses the program then asks the corresponding question. the user can input their answer and it the program needs to reply back with either correct or incorrect. my main problem is getting the program to recognize the actual math being done in the background and be able to check the answer the user inputs as correct or incorrect. here is my code so far. any help is greatly appreciated.

import javax.swing.JOptionPane;

public class elementarymath 
{
	private String inputString;
	public static int response;
	private int simple_math, simple_answer, num1, num2, add_eq, sub_eq;

	public void userChoice()
	{
		inputString = JOptionPane.showInputDialog("Would you like to practice:\n1. Addition\n2. Subtraction");
		simple_math = Integer.parseInt(inputString);
		simple_answer = Integer.parseInt(inputString);
		num1 = RandomNumber();
		num2 = RandomNumber();

		switch(simple_math)
		{
			case 1:
				JOptionPane.showInputDialog("Solve the following addition problem: \n" + num1 + " + " + num2 + " = "); //if user chooses 1 then do this
				break;
			case 2:
				JOptionPane.showInputDialog("Solve the following subtraction problem: \n" + num1 + " - " + num2 + " = "); //if user chooses 2 then do this
				break;
		}
		switch(simple_answer)
		{
			case 1:
				elementarymath.response = JOptionPane.showConfirmDialog(null, "You got it right! Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
				break;
			case 2:
				elementarymath.response = JOptionPane.showConfirmDialog(null, "I'm sorry, but that is incorrect. Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
				break;
		}
	}
	public int RandomNumber()
	{
		return ((int) (Math.random() * 10)); //generates random number and multiplies by ten
	}
	public static void main(String[] args)
	{
		elementarymath x = new elementarymath();
		do
		{
			x.userChoice();
		}
		while (response == 0);

		System.exit(0);
	}
}


----------



## YinYang.ERROR (Sep 10, 2009)

I'm guessing this is a simple GUI app, probably for class. As I have really no idea about GUI coding in Java, I'm not sure how much help I would be.

But I'm guessing your going to need to check if num1 + num2 (or num1 - num2)  is equal to the answer the user inputs.

but again I'm not 100% sure what you are doing with that code. I don't know what exactly this function is doing: Integer.parseInt(inputString);


Also, what is the purpose of the simple_math and simple_answer variables?


----------



## FordGT90Concept (Sep 10, 2009)

simple_answer will always equal 1 or 2.


I think...

Replace this:

```
inputString = JOptionPane.showInputDialog("Would you like to practice:\n1. Addition\n2. Subtraction");
simple_math = Integer.parseInt(inputString);
simple_answer = Integer.parseInt(inputString);
num1 = RandomNumber();
num2 = RandomNumber();

switch(simple_math)
{
case 1:
JOptionPane.showInputDialog("Solve the following addition problem: \n" + num1 + " + " + num2 + " = "); //if user chooses 1 then do this
break;
case 2:
JOptionPane.showInputDialog("Solve the following subtraction problem: \n" + num1 + " - " + num2 + " = "); //if user chooses 2 then do this
break;
}
```

With this:

```
inputString = JOptionPane.showInputDialog("Would you like to practice:\n1. Addition\n2. Subtraction");
simple_math = Integer.parseInt(inputString);
num1 = RandomNumber();
num2 = RandomNumber();

switch(simple_math)
{
case 1:
JOptionPane.showInputDialog("Solve the following addition problem: \n" + num1 + " + " + num2 + " = "); //if user chooses 1 then do this
simple_answer = num1 + num2;
break;
case 2:
JOptionPane.showInputDialog("Solve the following subtraction problem: \n" + num1 + " - " + num2 + " = "); //if user chooses 2 then do this
simple_answer = num1 - num2;
break;
}
```

simple_answer should then contain the correct answer.


The second switch statement won't work.  You need a boolean condition there...

if (simple_answer == userinput)
 //correct
else
 //incorrect


----------



## YinYang.ERROR (Sep 10, 2009)

^ yeah,

then he would have to turn this:

```
switch(simple_answer)
{
case 1:
elementarymath.response = JOptionPane.showConfirmDialog(null, "You got it right! Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
break;
case 2:
elementarymath.response = JOptionPane.showConfirmDialog(null, "I'm sorry, but that is incorrect. Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
break;
}
```

into an if/else which checks if simple_answer is equal to what he input.


Edit: DAMN YOUR NINJA EDITS!


----------



## FordGT90Concept (Sep 10, 2009)

Hiya!


----------



## Easy Rhino (Sep 10, 2009)

thanks guys for the quick reply. i will try this out soon. i actually have a couple of weeks to work on it and i think the professor is actually going to finish teaching us how to do it next week. but i figure better to get a jump on it now so i know what kinds of questions to ask in class.


----------



## Easy Rhino (Sep 10, 2009)

alright so i replaced the second switch statement with an if/else statement. however i am not sure how to add the condition. i know that if simple_add == userinput but i need to somehow identify userinput as the right answer. here is my new code.


```
import javax.swing.JOptionPane;

public class elementarymath 
{
	private String inputString;
	public static int response;
	private int simple_math, simple_answer, num1, num2, add_eq, sub_eq;

	public void userChoice()
	{
		inputString = JOptionPane.showInputDialog("Would you like to practice:\n1. Addition\n2. Subtraction");
		simple_math = Integer.parseInt(inputString);
		simple_answer = Integer.parseInt(inputString);
		num1 = RandomNumber();
		num2 = RandomNumber();
		
		switch(simple_math)
		{
			case 1:
				JOptionPane.showInputDialog("Solve the following addition problem: \n" + num1 + " + " + num2 + " = "); //if user chooses 1 then do this
				simple_answer = num1 + num2;
				break;
			case 2:
				JOptionPane.showInputDialog("Solve the following subtraction problem: \n" + num1 + " - " + num2 + " = "); //if user chooses 2 then do this
				simple_answer = num1 - num2;
				break;
		}
		if (simple_answer == )
		{
			elementarymath.response = JOptionPane.showConfirmDialog(null, "You got it right! Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
		}
		else
		{
			elementarymath.response = JOptionPane.showConfirmDialog(null, "I'm sorry, but that is incorrect. Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
		}
	}
	public int RandomNumber()
	{
		return ((int) (Math.random() * 10)); //generates random number and multiplies by ten
	}
	public static void main(String[] args)
	{
		elementarymath x = new elementarymath();
		do
		{
			x.userChoice();
		}
		while (response == 0);
		
		System.exit(0);
	}
}
```


----------



## FordGT90Concept (Sep 10, 2009)

These two should return the response from the user.

```
JOptionPane.showInputDialog("Solve the following addition problem: \n" + num1 + " + " + num2 + " = "); //if user chooses 1 then do this
JOptionPane.showInputDialog("Solve the following subtraction problem: \n" + num1 + " - " + num2 + " = "); //if user chooses 2 then do this
```
Just as it does here:

```
inputString = JOptionPane.showInputDialog("Would you like to practice:\n1. Addition\n2. Subtraction");
```
You need only compare the stored answer to the answer given by the user (make sure to convert to the same type first).


You could add a "correct" boolean variable and determine whether or not it is correct inside your switch statement.  That would probably be the easiest.

Example:

```
int correct = false;
switch (choice)
{
  case 1:
    if (Integer.parseInt(OptionPane.showInputDialog("Solve the following addition problem: \n" + num1 + " + " + num2 + " = ")) == Integer.parseInt(num1 + num2))
      correct = true;
    break;
}
if (correct)
  // correct message
else
  // incorrect message
```
That second Integer.parseInt() is there to make certain Java didn't turn it into a double or some other mathematical form which could erroneously return false.


----------



## Easy Rhino (Sep 10, 2009)

FordGT90Concept said:


> These two should return the response from the user.
> 
> ```
> JOptionPane.showInputDialog("Solve the following addition problem: \n" + num1 + " + " + num2 + " = "); //if user chooses 1 then do this
> ...



this is how i am approaching it. but i get the error "type mismatch: cannot convert from string to int"

here is my new code so you can see exactly what i am trying to do.


```
import javax.swing.JOptionPane;

public class elementarymath 
{
	private String inputString;
	public static int response;
	private int simple_math, simple_answer, num1, num2, correct_answer;

	public void userChoice()
	{
		inputString = JOptionPane.showInputDialog("Would you like to practice:\n1. Addition\n2. Subtraction");
		simple_math = Integer.parseInt(inputString);
		simple_answer = Integer.parseInt(inputString);
		num1 = RandomNumber();
		num2 = RandomNumber();
		correct_answer = inputString;
		
		switch(simple_math)
		{
			case 1:
				JOptionPane.showInputDialog("Solve the following addition problem: \n" + num1 + " + " + num2 + " = "); //if user chooses 1 then do this
				simple_answer = num1 + num2;
				break;
			case 2:
				JOptionPane.showInputDialog("Solve the following subtraction problem: \n" + num1 + " - " + num2 + " = "); //if user chooses 2 then do this
				simple_answer = num1 - num2;
				break;
		}
		if (simple_answer == correct_answer)
		{
			elementarymath.response = JOptionPane.showConfirmDialog(null, "You got it right! Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
		}
		else
		{
			elementarymath.response = JOptionPane.showConfirmDialog(null, "I'm sorry, but that is incorrect. Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
		}
	}
	public int RandomNumber()
	{
		return ((int) (Math.random() * 10)); //generates random number and multiplies by ten
	}
	public static void main(String[] args)
	{
		elementarymath x = new elementarymath();
		do
		{
			x.userChoice();
		}
		while (response == 0);
		
		System.exit(0);
	}
}
```


----------



## FordGT90Concept (Sep 10, 2009)

You still aren't doing anything with the responses from the two "Solve the following addition problem" dialogs.

Must fix. 


Edit: type mismatch is because string can't be compared to int without first being of the same type.  That is, int and int or string and string.  In your case, I think you would want to convert the string to an int using Integer.parseInt().  You may want to consider changing it to floats/singles or doubles though otherwise decimals will cause an error.


----------



## Easy Rhino (Sep 10, 2009)

FordGT90Concept said:


> You still aren't doing anything with the responses from the two "Solve the following addition problem" dialogs.
> 
> Must fix.
> 
> ...



sorry im lost now


----------



## FordGT90Concept (Sep 10, 2009)

I really shouldn't be coding it for you. 

Clarify "lost."


----------



## Easy Rhino (Sep 10, 2009)

FordGT90Concept said:


> I really shouldn't be coding it for you.
> 
> Clarify "lost."



yea i agree. could you point me to some reference material for what i am struggling with?


----------



## FordGT90Concept (Sep 10, 2009)

Google? XD

To clear up some confusion, I combined all my suggestions with your original code here and commented it.  Note that I don't have a Java compiler installed so I didn't try compiling it.  It probably isn't perfect but should be close enough to give you an idea:

```
import javax.swing.JOptionPane;

public class elementarymath 
{
	public static int response;
	
	public void userChoice()
	{
		// Get the choice, convert it to integer, and store it.
		int choice = Integer.parseInt(JOptionPane.showInputDialog("Would you like to practice:\n1. Addition\n2. Subtraction"));

		// Randomize values...
		double a = RandomNumber();
		double b = RandomNumber();

		// These are variables that are needed in, and referenced outside of, the switch...
		double user_answer = 0;  // We'll store the user inputted answer here.
		double comp_answer = 0;  // We'll store the computer calculated answer here
		Boolean correct = false; // This determines whether or not we consider the two above to match.

		switch(choice)
		{
			case 1: // Addition
				user_answer = Double.parseDouble(JOptionPane.showInputDialog("Solve the following addition problem: \n" + a + " + " + b + " = "));
				comp_answer = a + b;
				if (user_answer == comp_answer)
				{
					correct = true;
				}
				break;
			case 2: // Subtraction
				user_answer = Double.parseDouble(JOptionPane.showInputDialog("Solve the following subtraction problem: \n" + a + " - " + b + " = "));
				comp_answer = a - b;
				if (user_answer == comp_answer)
				{
					correct = true;
				}
				break;
		}

		if (correct)
		{
			// It's correct
			elementarymath.response = JOptionPane.showConfirmDialog(null, "You got it right! Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
		}
		else
		{
			// It's incorrect
			elementarymath.response = JOptionPane.showConfirmDialog(null, "I'm sorry, but that is incorrect. Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
		}
	}

	// Changed this to double to prevent dataloss.
	public double RandomNumber()
	{
		// Generate a random and round to the closest whole number.
		return Math.rint(Math.random());
	}

	// Below this point is unchanged
	public static void main(String[] args)
	{
		elementarymath x = new elementarymath();
		do
		{
			x.userChoice();
		}
		while (response == 0);

		System.exit(0);
	}
}
```

You could display the computational answer if the user answer wasn't correct in that incorrect dialog.


----------



## YinYang.ERROR (Sep 10, 2009)

FordGT90Concept said:


> Google? XD
> 
> To clear up some confusion, I combined all my suggestions with your original code here and commented it.  Note that I don't have a Java compiler installed so I didn't try compiling it.  It probably isn't perfect but should be close enough to give you an idea:




+1

Good Job FordGT90Concept! 

It looks ok to me.


----------



## Easy Rhino (Sep 10, 2009)

FordGT90Concept said:


> Google? XD
> 
> To clear up some confusion, I combined all my suggestions with your original code here and commented it.  Note that I don't have a Java compiler installed so I didn't try compiling it.  It probably isn't perfect but should be close enough to give you an idea:
> 
> ...



thanks. i compiled it and ran it and it works i just had to turn some things around. im adjusting my code to add the if/else statements properly. we are still learning that stuff. you have Double.parseDouble what would i do to change that to int as i want all numbers to be single digits.

edit! nevermind i figured it out. Integer.parseInt

thanks a ton! now that i know how to put together a decent if/else i will be able to ask some good questions next week and be ahead of the game. i owe you a beer. now what if i want to make it so that with subtraction there cannot be any negative numbers? it would mean that the larger number is always first. so perhaps i need to make another 

int num3 = RandomNumber()

but have it always be >= 0

or i could just somehow make num1 > or = 0


----------



## FordGT90Concept (Sep 10, 2009)

.NET uses Math.Sign but it appears Java doesn't have that.  Quick writeup of equivilent:

```
// Returns -1 if value is negative, 1 if value is positive, and 0 if value is 0.
public static int Sign(double value)
{
  if (value > 0)
  {
    return 1;
  }
  else if (value < 0)
  {
    return -1;
  }
  else
  {
    return 0;
  }
}
```


Double can handle negatives so you don't _have_ to handle it.  If you want it to be inside of a certain range, just modify the RandomNumber() method.



Remember, if you Integer.parseInt() to one side, make sure you do the same to the other.  It might not be equal if you don't.


Example of direct edit to RandomNumber():

```
public double RandomNumber()
	{
		double rand = -1;  // Forces it to enter the while loop.
		while (rand < 0)
		{
			// Generate a random number until positive.
			rand = Math.rint(Math.random());
		}
		return rand;
	}
```

Edit: I think you would want to put swap code inside of the subtraction case if that's what you want to do.  Something like...


```
case 2: // Subtraction
				if (b > a)
				{
					double temp = b;
					b = a;
					a = temp;
				}
				user_answer = Double.parseDouble(JOptionPane.showInputDialog("Solve the following subtraction problem: \n" + a + " - " + b + " = "));
				comp_answer = a - b;
				if (user_answer == comp_answer)
				{
					correct = true;
				}
				break;
```


----------



## Easy Rhino (Sep 10, 2009)

well i have everything worked out. but i need num1 to always be larger than num2. this is the easiest way to assure that there will never be a negative answer for the subtraction problems. i was thinking something like 

num1 > num2 

but that yields syntax error invalid assignment operator


----------



## FordGT90Concept (Sep 10, 2009)

Look at the bottom of my last post (after the edit).  The little if statement there should take care of it no matter where you need it (at least in theory).  It is a simple swap before the user even knows it happened.


----------



## Easy Rhino (Sep 10, 2009)

FordGT90Concept said:


> Look at the bottom of my last post (after the edit).  The little if statement there should take care of it no matter where you need it (at least in theory).  It is a simple swap before the user even knows it happened.



damn man. i cant wait to actually learn this stuff in class.


----------



## FordGT90Concept (Sep 10, 2009)

You mean you aren't learning it now?


----------



## Easy Rhino (Sep 10, 2009)

FordGT90Concept said:


> You mean you aren't learning it now?



well yea! sorry i didnt mean it that way!!! i am learning it while you show me the way to do it. that is how i learn. i just meant when we get to the section in class next week that explains it all out in detail.


----------



## Easy Rhino (Sep 14, 2009)

i have decided to take a bit of a leap and add a way for the program to keep tabs on how many questions have been answered correctly. it was fairly simple to figure out, however the problem is with the program. when the question has been answered it asks if you want to solve another problem and then if you answer yes it simply restarts the program from the beginning and looses the value! here is what i have so far so far i want it to simply add 1 to the total_correct value and it is doing it with total_correct++ but like i said it looses that value when asking a new question.


```
import javax.swing.JOptionPane;

public class elementarymath 
{
	private String inputString;
	public static int response;
	private int simple_math;

	public void userChoice()
	{
		inputString = JOptionPane.showInputDialog("Would you like to practice:\n1. Addition\n2. Subtraction");
		simple_math = Integer.parseInt(inputString);
		int num1 = RandomNumber();
		int num2 = RandomNumber();
		int user_answer = 0;
		int correct_answer = 0;
		int total_correct = 0; 
		boolean correct = false;
		
		switch(simple_math)
		{
			case 1: //addition
				user_answer = Integer.parseInt(JOptionPane.showInputDialog("Solve the following addition problem: \n" + num1 + " + " + num2 + " = ")); 
				correct_answer = num1 + num2;
				if (user_answer == correct_answer)
				{
					correct = true;
					correct_answer = total_correct++;
				}
				break;
			case 2: //subtraction
				if (num1 < num2)
				{
					int num3 = num1;
					num2 = num1;
					num1 = num3;
				}
				user_answer = Integer.parseInt(JOptionPane.showInputDialog("Solve the following subtraction problem: \n" + num1 + " - " + num2 + " = "));
				correct_answer = num1 - num2;
				if (user_answer == correct_answer)
				{
					correct = true;
				}
				break;
		}
		if(correct)
		{
			elementarymath.response = JOptionPane.showConfirmDialog(null, "You got it right! You have answered " + total_correct + " question correctly.\n Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
		}
		else
		{
			elementarymath.response = JOptionPane.showConfirmDialog(null, "I'm sorry, but that is incorrect. Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
		}
	}
	public int RandomNumber()
	{
		return ((int) (Math.random() * 10)); //generates random number and multiplies by ten
	}
	public static void main(String[] args)
	{
		elementarymath x = new elementarymath();
		do
		{
			x.userChoice();
		}
		while (response == 0);
		
		System.exit(0);
	}
}
```


----------



## FordGT90Concept (Sep 14, 2009)

Mainly, you just have to move total_correct outside of the sub to a class-level variable...

```
import javax.swing.JOptionPane;

public class elementarymath 
{
	private String inputString;
	public static int response;
	public int total_correct;  // Stuck it here gaining access to it from outside the sub.
	private int simple_math;

	// Added this constructor to set the value of this instance of total_correct
	public elementarymath()
	{
		total_correct = 0;
	}


	public void userChoice()
	{
		inputString = JOptionPane.showInputDialog("Would you like to practice:\n1. Addition\n2. Subtraction");
		simple_math = Integer.parseInt(inputString);
		int num1 = RandomNumber();
		int num2 = RandomNumber();
		int user_answer = 0;
		int correct_answer = 0;
		// Removed it from here and moved to a class-level variable.
		boolean correct = false;
		
		switch(simple_math)
		{
			case 1: //addition
				user_answer = Integer.parseInt(JOptionPane.showInputDialog("Solve the following addition problem: \n" + num1 + " + " + num2 + " = ")); 
				correct_answer = num1 + num2;
				if (user_answer == correct_answer)
				{
					correct = true;
					correct_answer = total_correct++;
				}
				break;
			case 2: //subtraction
				if (num1 < num2)
				{
					int num3 = num1;
					num2 = num1;
					num1 = num3;
				}
				user_answer = Integer.parseInt(JOptionPane.showInputDialog("Solve the following subtraction problem: \n" + num1 + " - " + num2 + " = "));
				correct_answer = num1 - num2;
				if (user_answer == correct_answer)
				{
					correct = true;
				}
				break;
		}
		if(correct)
		{
			total_correct++; // Increment it here.
			elementarymath.response = JOptionPane.showConfirmDialog(null, "You got it right! You have answered " + total_correct + " question correctly.\n Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
		}
		else
		{
			elementarymath.response = JOptionPane.showConfirmDialog(null, "I'm sorry, but that is incorrect. Would you like to continue practicing?\n", "Addition and Subtraction Problems", JOptionPane.YES_NO_OPTION);
		}
	}
	public int RandomNumber()
	{
		return ((int) (Math.random() * 10)); //generates random number and multiplies by ten
	}
	public static void main(String[] args)
	{
		elementarymath x = new elementarymath();  // This line calls the constructor above.
		do
		{
			x.userChoice();
		}
		while (response == 0);

		// Show the value of total_correct before closing using x.total_correct
		
		System.exit(0);
	}
}
```

This is only a way to do it; there are many others.


----------



## Easy Rhino (Sep 14, 2009)

damn dude, you are a genious!!!!


----------



## Easy Rhino (Sep 23, 2009)

got a new small program that i finished but im having decimal issues. essentially it keeps cutting off the last "0" in the digits even tho i have DecimalFormat set to "0.0" and it is keeping the last counting to the thousandths place...

```
import java.io.*;
import java.text.DecimalFormat;

public class exam1 
{
	private BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
	
	DecimalFormat oneDecimal = new DecimalFormat("0.0");
	
	private String input_string;
	private double purchase_order, total_charge, initial_charge, bags_purchased, discount;
	
	public void user_interface() throws IOException
	{
		System.out.println("How many bags of delicious coffee would you like to purchase?");
		input_string = keyboard.readLine();
		bags_purchased = Double.parseDouble(input_string);
		
			if(bags_purchased < 25)
			{
				initial_charge = bags_purchased * 5.50;
				discount = initial_charge * 0.00;
				total_charge = initial_charge - discount;
			}
			if(bags_purchased >= 25)
			{
				initial_charge = bags_purchased * 5.50;
				discount = initial_charge * 0.05;
				total_charge = initial_charge - discount;
			}
			if(bags_purchased >= 50)
			{
				initial_charge = bags_purchased * 5.50;
				discount = initial_charge * 0.10;
				total_charge = initial_charge - discount;
			}
			if(bags_purchased >= 100)
			{
				initial_charge = bags_purchased * 5.50;
				discount = initial_charge * 0.15;
				total_charge = initial_charge - discount;
			}
			if(bags_purchased >= 150)
			{
				initial_charge = bags_purchased * 5.50;
				discount = initial_charge * 0.20;
				total_charge = initial_charge - discount;
			}
			if(bags_purchased >= 200)
			{
				initial_charge = bags_purchased * 5.50;
				discount = initial_charge * 0.25;
				total_charge = initial_charge - discount;
			}
			if(bags_purchased >= 300)
			{
				initial_charge = bags_purchased * 5.50;
				discount = initial_charge * 0.30;
				total_charge = initial_charge - discount;
			}
		System.out.println("Number of Bags Ordered: " + bags_purchased + " - $" + initial_charge);
		System.out.println("Discount: $" + discount ++);
		System.out.println("Your total charge is: $" + total_charge + "");
	}
	public static void main(String[] args) throws IOException
	{
		exam1 x = new exam1();
			x.user_interface();
	}
}
```


----------



## twilyth (Sep 23, 2009)

I'm just learning java, but don't you have to recast it or something?  When you go to print a double, what is the default conversion?  I'm guessing int maybe?


----------



## FordGT90Concept (Sep 23, 2009)

You got to use oneDecimal.format(value) to make use of that formatter.  You are defining, but not using it.

e.g.

```
System.out.println("Number of Bags Ordered: " + bags_purchased + " - $" + oneDecimal.format(initial_charge));
		System.out.println("Discount: $" + oneDecimal.format(discount) ++);
		System.out.println("Your total charge is: $" + oneDecimal.format(total_charge) + "");
```

If you don't use a formatter, it will return the default string for the type.


----------



## Easy Rhino (Oct 7, 2009)

im attempting to use arrays...

essentially i need to enter info for three separate fields into an array and have the program spit the data i entered back out to me. i can enter the data but it gives me an exception when it tries to print it...  here is what i have so far. it is in 3 diff classes...


```
import java.util.StringTokenizer;

public class Employee 
{
	String employeeName, employeeSalary, employeeDepartment;
	String employee3;
	String[] employeeArray = new String[3];
	int subScript = 0;
	
	public void splitUpEmployee(String employee1)
	{
		StringTokenizer st = new StringTokenizer(employee1);
		employeeName = st.nextToken();
		employeeSalary = st.nextToken();
		employeeDepartment = st.nextToken();
	}
	
	public void addToArray(String employee2)
	{
		employeeArray[subScript] = employee2;
		subScript++;
	}
	
	public void extractFromArray()
	{
		employee3 = employeeArray[subScript];
		splitUpEmployee(employee3);
		subScript++;
	}
	
	public void initializeCounter()
	{
		subScript = 0;
	}
}
```


```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Manager extends Employee
{
	private int n;
	private String inputString;
	private final BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
	
	public void user_interface() throws IOException
	{
		n = 0;
		while (n < 1)
		{
			System.out.println("Enter employee name: ");
			inputString = keyboard.readLine();
			addToArray(inputString);
			System.out.println("Enter employee department: ");
			inputString = keyboard.readLine();
			addToArray(inputString);
			System.out.println("Enter employee salary: ");
			inputString = keyboard.readLine();
			addToArray(inputString);
			n++;
		}
	}
	
	public void outputData() throws IOException
	{
		n = 0;
		subScript = 0;
		while (n < 1)
		{
			extractFromArray();
			System.out.println("Employee Name: " + employeeName);
			System.out.println("Employee Department: " + employeeDepartment);
			System.out.println("Employee Salary: " + employeeSalary);
			n++;
		}
	}

}
```


```
import java.io.*;

public class testproject3 
{
	public static void main(String[] args) throws IOException
	{
		Manager x = new Manager();
		x.user_interface();
		x.outputData();
	}

}
```


----------



## FordGT90Concept (Oct 7, 2009)

What's the exception?


----------



## Easy Rhino (Oct 7, 2009)

ok i changed some code around. when i enter employee info i enter the name<space>department<space>and salary and the next.Token() essentially breaks that down into 3 fields using the space as the delimiter. It spits back 
name: name i entered
department: null
salary: department i entered

part of the assignment is to put the department field in a different class to practice using "extends." so i need to get the program to assign department correctly. here is what i have.


```
import java.util.StringTokenizer;

public class Employee 
{
	String employeeName, employeeSalary;
	String employee3;
	String[] employeeArray = new String[3];
	int subScript = 0;
	
	public void splitUpEmployee(String employee1)
	{
		StringTokenizer st = new StringTokenizer(employee1);
		employeeName = st.nextToken();
		employeeSalary = st.nextToken();
	}
	
	public void addToArray(String employee2)
	{
		employeeArray[subScript] = employee2;
		subScript++;
	}
	
	public void extractFromArray()
	{
		employee3 = employeeArray[subScript];
		splitUpEmployee(employee3);
		subScript++;
	}
	
	public void initializeCounter()
	{
		subScript = 0;
	}
}
```


```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Manager extends Employee
{
	private int n;
	public String employeeDepartment;
	private String inputString;
	private final BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
	
	public void addDepartment(String employee1)
	{
		StringTokenizer st = new StringTokenizer(employee1);
		employeeDepartment = st.nextToken();
	}
	
	public void user_interface() throws IOException
	{
		n = 0;
		while (n < 1)
		{
			System.out.println("Enter employee name, department and salary: ");
			inputString = keyboard.readLine();
			addToArray(inputString);
			n++;
		}
	}
	
	public void outputData() throws IOException
	{
		n = 0;
		subScript = 0;
		while (n < 1)
		{
			extractFromArray();
			System.out.println("Employee Name: " + employeeName);
			System.out.println("Employee Department: " + employeeDepartment);
			System.out.println("Employee Salary: " + employeeSalary);
			n++;
		}
	}

}
```


```
import java.io.*;

public class testproject3 
{
	public static void main(String[] args) throws IOException
	{
		Manager x = new Manager();
		x.user_interface();
		x.outputData();
	}

}
```


----------



## FordGT90Concept (Oct 7, 2009)

So, what's wrong with it now?

Also, I'd recommend using some other character as a delimitter.  Space is common.  I like using tlide (~) or the bar (|) and make sure those chars are rejected as input.


----------



## Easy Rhino (Oct 7, 2009)

FordGT90Concept said:


> So, what's wrong with it now?
> 
> Also, I'd recommend using some other character as a delimitter.  Space is common.  I like using tlide (~) or the bar (|) and make sure those chars are rejected as input.



it returns null for the department field. im guessing it has something to do with how i have the department field setup. i tried to write it so that the department field is parto of the EmployeeArray. obviously i am missing something.


----------



## FordGT90Concept (Oct 7, 2009)

```
n = 0;
		while (n < 1)
		{
			System.out.println("Enter employee name, department and salary: ");
			inputString = keyboard.readLine();
			addToArray(inputString);
			n++;
		}
```
That while loop will only execute once so your array will only ever have an item at index 0.

If you are trying to populate an array (which you are), you should always use Array.getLength() so that the indexor will never exceed the number of indexes in the array.


FYI: Name, Department, and salary should really be properties of the Employee class, not an array.  A good candidate for an array, for example, is the lines of an address.  Name should be two strings (first and last), Department should be an enumerator, and Salary should be a double or float.



Example of what I think you are trying to do:

```
public static String[] user_interface() throws IOException
	{
		System.out.println("New Manager...");
		String[] output = new String[] = { "Name", "Department", "Salary" };
		for (int i = 0; i < output.getLength(); i++)
		{
			System.out.println("Enter " + output[i] + ": ");
			output[i] = keyboard.readLine();
		}
		return output;
	}
```
Most likely in your Main method, you would do this:

```
Manager e = new Manager(Manager.user_interface());
```
That would prompt for the information and create a new instance of Employee.  The Employee constructor would accept an array of strings and break it out into its respective parts (make sure the array is the correct length and throw an exception if it is not).


----------



## Easy Rhino (Oct 8, 2009)

i dont know. im completely lost now  my prof didn't do a very good job of providing examples for this project.  im trying to create and define an array and i keep getting syntax errors. this is how you make an array right?


```
String Array[] = new String[3];             
Array[0] = new String(employeeName);
Array[1] = new String(employeeDepartment);
Array[2] = new String(employeeSalary);
```

but i get a syntax error on the first line. it wants a { instead of a ;

it wants me to create a block for this even tho every example in my book shows otherwise. and when i do insert a { it makes me chane all my ; to , and then it messes up all the blocks. something is screwy.


----------



## FordGT90Concept (Oct 8, 2009)

```
String[] fields = new String[3];
fields[0] = employeeName;
fields[1] = employeeDepartment;
fields[2] = employeeSalary;
```
...assuming employeeName, employeeDepartment, and employeeSalary are already defined as strings...

WHERE
String = type
[] = an array of type
fields = name of the array
new String[3] = initialize a new array of Strings with three null indices.  fields.getLength() will return 3
fields[0] = index zero of the fields array
fields[1] = index one of the fields array
fields[2] = index two of the fields array


A way to condense those four lines into one:

```
String[] fields = { employeeName, employeeDepartment, employeeSalary };
```

More information on arrays can be found here:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html



Indicies are always zero-based.  Counting numbers are always 1 based.  Counting numbers are used for the Length and not much else.


----------



## Easy Rhino (Oct 12, 2009)

ok i am pretty much finished with this array project. i set up 2 classes. 1 is an employee class with an array of 2 subscripts and the other is a manager class with an array of 3 subscripts. both have methods to enter and extract data from their respective classes. now i am writing the class for the main method called TestProgram. i instantiate TestProgram with the typical command and then i want to execute the program using a method i created that allows the user to choose which array he wants to enter information for. so...


```
public static void main(String[] args)
	{
		TestProgram x = new TestProgram();
		x.user_choice();
	}
```

instantiates the TestProgram class and will run the user_choice method. i want the user_choice method to call either the user_interfaceEmployee() or the user_interfaceManager(). 


```
public void user_choice()
	{
		userInput = System.out.println("Enter 1 to enter manager info or 2 to enter employee info.");
		chooseOne = Integer.parseInt(userInput);
		
		switch(chooseOne)
		{
		case 1:
			x.user_interfaceManager;
			x.outputDataManager;
		case 2:
			x.user_interfaceEmployee;
			x.outputDataEmployee();
		}
	}
```

but as you can imagine it says it cannot resolve x for these cases. any ideas? is this not even possible? should i move some of the code around? here are the employee and manager classes.


```
import java.util.StringTokenizer;

public class Employee
{
	String employeeName, employeeSalary;
	String employee3;
	int subScript = 0;
	String[] employeeArray = new String[2];
	
	public void splitUpEmployee(String employee1)
	{
		StringTokenizer emp = new StringTokenizer(employee1);
		employeeName = emp.nextToken();
		employeeSalary = emp.nextToken();
	}
	
	public void addToEmployeeArray(String employee2)
	{
		employeeArray[subScript] = employee2;
		subScript++;
	}
	
	public void extractFromEmployeeArray()
	{
		employee3 = employeeArray[subScript];
		splitUpEmployee(employee3);
		subScript++;
	}
	
	public void initializeCounter()
	{
		subScript = 0;
	}
}//end Employee class
```


```
import java.util.StringTokenizer;

public class Manager extends Employee
{
	String managerName, managerSalary, managerDepartment;
	String manager3;
	int subScript = 0;
	String[] managerArray = new String[3];
		
	public void splitUpManager(String manager1)
	{
		StringTokenizer man = new StringTokenizer(manager1);
		managerName = man.nextToken();
		managerSalary = man.nextToken();
		managerDepartment = man.nextToken();
		subScript++;
	}
	
	public void addToManagerArray(String manager2)
	{
		managerArray[subScript] = manager2;
		subScript++;
	}
	
	public void extractFromManagerArray()
	{
		manager3 = managerArray[subScript];
		splitUpManager(manager3);
		subScript++;
	}
	
	public void initializeCounter()
	{
		subScript = 0;
	}
	
	
}//end Manager class
```


----------



## PP Mguire (Oct 12, 2009)

*Really hope i dont get in trouble for that *


----------



## FordGT90Concept (Oct 12, 2009)

If TestProgram isn't an instance of a Manager or Employee then you just need to instantiate your Manager or Employee in the switch:

```
public void user_choice()
	{
		userInput = System.out.println("Enter 1 to enter manager info or 2 to enter employee info.");
		chooseOne = Integer.parseInt(userInput);
		
		switch(chooseOne)
		{
		case 1:
			Manager manager = new Manager();
			manager.user_interfaceManager;
			manager.outputDataManager;
			break;
		case 2:
			Employee employee = new Employee();
			employee.user_interfaceEmployee;
			employee.outputDataEmployee();
			break;
		}
	}
```


----------



## Easy Rhino (Oct 12, 2009)

what i did was move the user_interfaceEmployee, outputDataEmployee to the Employee class and moved the user_interfaceManager(), outputDataManager() to the Manager class. i added the lines you showed me in the case however when i run the program i can choose the 1 or 1 option and enter the info but i get...


```
Exception in thread "main" java.util.NoSuchElementException
	at java.util.StringTokenizer.nextToken(StringTokenizer.java:332)
	at Manager.splitUpManager(Manager.java:52)
	at Manager.extractFromManagerArray(Manager.java:66)
	at Manager.outputDataManager(Manager.java:40)
	at TestProgram.user_choice(TestProgram.java:19)
	at TestProgram.main(TestProgram.java:32)
```


----------



## FordGT90Concept (Oct 12, 2009)

The error is in here:

```
public void splitUpManager(String manager1)
	{
		StringTokenizer man = new StringTokenizer(manager1);
		managerName = man.nextToken();
		managerSalary = man.nextToken();
		managerDepartment = man.nextToken();
		subScript++;
	}
```
On line 52.  My guess is it doesn't like it what it was handed in "manager1."


----------



## Easy Rhino (Oct 12, 2009)

FordGT90Concept said:


> The error is in here:
> 
> ```
> public void splitUpManager(String manager1)
> ...



strangely i got it to work randomly. but sometimes i start the program i can choose option 1 or 2 and but then i cannot write anything in console. other times i can write in console. clearly i screwed something up.

EDIT! i fixed that bug. ok so i can get employee to work because i am not breaking down the inputStrings into catagories. i am just asking to enter information and it breaks it down using nextToken(). so i am ONE step away from finishing!


----------



## Easy Rhino (Oct 14, 2009)

project finished! it works so i hope i receive full credit. now onto the next project. this class moves fast... 

i am essentially creating a program that uses graphics. ive already created the JFrame no problem and have associated most of the necessary panels. the program requires the user to enter a word into an input dialog box and then put it on the JFrame. it is a word guessing game and if you guess 5 letters incorrectly you lose. so the user enters the secret word and i need the program to somehow break that word down by letter and mask it using *****. the guesser will then see the ***** and be asked to guess a letter until either they get it right or they lose.  im thinking about using an array to break down the user entered secret word. however i dont know how to get the word entered in the JOptionpane to go to my JPanel. this is what i have so far. ignore the actionPerformed method as i just have it there right now to get the program to actually execute. 


```
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class TimeBomb extends JFrame implements ActionListener
{
	private final JLabel lblTitle = new JLabel("Time Bomb Game!");
	private final JButton btnOK = new JButton("OK");
	private final JTextField tfInput = new JTextField(2);
	private final JLabel lblMessage = new JLabel("Enter A Letter: ");
	private final JLabel userWord = new JLabel("");
	
	String inputString;
	
	private char timebombArray[] = new char[8];
	
	public TimeBomb()//constructor for GUI
	{
		super("Time Bomb Game");
		
		inputString = JOptionPane.showInputDialog("Enter Secret Word: ");
		getContentPane().setLayout(new BorderLayout(1, 1));
		
		Font f = new Font("Dialog", Font.PLAIN, 24);
		lblTitle.setFont(f);
		lblMessage.setFont(f);
		tfInput.setFont(f);
		
		
		JPanel northPanel = new JPanel();
		northPanel.add(lblTitle);
		getContentPane().add(northPanel, "North");
		
		JPanel eastPanel = new JPanel();
		eastPanel.add(btnOK);
		getContentPane().add(eastPanel, "East");
		btnOK.addActionListener(this);
		
		JPanel centerPanel = new JPanel();
		centerPanel.add(tfInput);
		getContentPane().add(centerPanel, "Center");
		
		JPanel westPanel = new JPanel();
		westPanel.add(lblMessage);
		getContentPane().add(westPanel, "West");
		
		JPanel southPanel = new JPanel();
		southPanel.add(userWord);
		getContentPane().add(southPanel, "South");
	
		setSize(310, 200);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))
		{
			tfInput.setText("");
		}
	}
	
	public static void main(String[] args)
	{
		new TimeBomb();
	}
}//end TimeBomb class
```


----------



## FordGT90Concept (Oct 14, 2009)

I think if you take your string and treat it as an array, you'll get the char index out of it... e.g.

```
String mystring = "blamo";
mystring[0] // b
mystring[1] // l
mystring[2] // a
mystring[3] // m
mystring[4] // o
```
The alternative would be to break it down into a byte array:

```
String mystring = "blamo";
byte[] bytes = mystring.getBytes(); // Get the bytes from the string.
String mynewstring = new String(bytes); // Convert bytes back to a string.
```


----------



## Easy Rhino (Oct 14, 2009)

FordGT90Concept said:


> I think if you take your string and treat it as an array, you'll get the char index out of it... e.g.
> 
> ```
> String mystring = "blamo";
> ...


----------



## Kreij (Oct 15, 2009)

Sorry Easy, but I have not done any Java coding.
I just downloaded the JDK, so give me a couple of days to learn the language and I will be able to be of more help


----------



## Easy Rhino (Oct 15, 2009)

Kreij said:


> Sorry Easy, but I have not done any Java coding.
> I just downloaded the JDK, so give me a couple of days to learn the language and I will be able to be of more help



thanks. ive got 2 weeks to get this done. problem is we have another project assigned next week as well. so im trying to stay ahead of the game since i have a decent learning curve.


----------



## Easy Rhino (Oct 15, 2009)

ok this may be an easier way for me to break down the problems i am having. there are 3 big problems to accomplish and im taking them one at a time. the first is to get user input as a string and put it into an array of characters. i decided to write a small program to help me sort out the problem without messing with my JFrame code. here is what i have which attempts to take inputString from the keyboard which is input by the user using a dialog box and putting it into an array called timebombArray. i just cant figure out how to put it into the array since one is a String and the other is a char array.


```
import javax.swing.*;
import java.io.*;

public class ArrayDemo2 
{
	String inputString;
	private BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

	public void wordInput() throws IOException
	{
		inputString = JOptionPane.showInputDialog("Enter Word: ");
		inputString = keyboard.readLine();
	}
	
	char[] timebombArray = new char[9];
	
	
	public void wordOutput()
	{
		for(int i = 0; i < timebombArray.length; i++)
			System.out.println(timebombArray[i]);
	}
	
	
	public static void main(String[] args) throws IOException
	{
		ArrayDemo2 x = new ArrayDemo2();
		x.wordInput();
		x.wordOutput();
	}//end of main
}//end of class
```


----------



## Kreij (Oct 15, 2009)

I'm not sure on this in Java.
In C# a string is basically a character array.
So I can say..

```
string myString = "Vent";
myString[0] = "B";
```

The resulting string in myString will equal "Bent".


----------



## Easy Rhino (Oct 15, 2009)

Kreij said:


> I'm not sure on this in Java.
> In C# a string is basically a character array.
> So I can say..
> 
> ...



yes exactly, but in my case the String literal value isn't preset, it is actually set when the user inputs the word into the dialog box. that is what i am having trouble with.


----------



## FordGT90Concept (Oct 15, 2009)

I've done something similar before and what I did was create masks...

Step 1: Count the number of unique characters in the string. e.g. "blamo" has five unique characters.

Step 2: Create a "Mask" class or struct which has two definitions in it: 1) A String or char that represents this mask and 2) a String which holds the mask for that character.

Step 3: Create an array of class "mask", one for each unique character.  Everything not that character has an underscore.  e.g. "b____", "_l___", "__a__" etc.

Step 4: Make a MergeMask class which accepts two masks (or strings) and returns one string.  This is a simple for loop where if value not equal to an underscore, copy to the output string.  e.g. "b____" and "__a__" returns "b_a__"

Step 5: When they type a character, search your Mask array for a match.  If no match, that's a strike against them.  If it is a match you use the Step 4 method to make an output value.


I just checked how to get a char from a string:

```
String mystring = "blamo";
mystring.charAt(4); // 'o'
mystring.charAt(0); // 'b'
```

You could always stick to a byte array too.  It's easy to convert from string, to bytes, and back to string.


----------



## Easy Rhino (Oct 15, 2009)

im getting there. ive been at it for 8 hours today and i am learning a lot! mad:

here is my code. i can return a length which is easy enough. but i need to return the inputString in an array format which is possible with strings. i just dont know how how yet...


```
import java.io.*;

public class ArrayDemo2 
{
	String inputString;

	private BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
	
	public void wordInput() throws IOException
	{
		System.out.println("Enter Word: ");
		inputString = keyboard.readLine();
		System.out.println("Your word has this many letters: " + inputString.length());
	}
	
	public static void main(String[] args) throws IOException
	{
		ArrayDemo2 x = new ArrayDemo2();
		x.wordInput();

	}//end of main
}//end of class
```


----------



## Easy Rhino (Oct 15, 2009)

FordGT90Concept said:


> I've done something similar before and what I did was create masks...
> 
> Step 1: Count the number of unique characters in the string. e.g. "blamo" has five unique characters.
> 
> ...



wow you posted this just as i updated my posting. the charAt() is going to come in very handy. i figure im going to keep it simple. im going to use the readLine() to get user's secret word and then output it as a mask.

now i just need to figure out how to get a String into a JFrame.


----------



## FordGT90Concept (Oct 15, 2009)

JLabel <- Just display a message
JTextArea <- Multiline text input
JTextField <- Single line text input

Full list here.

This article has an example of how to add components to a JFrame.


----------



## Easy Rhino (Oct 15, 2009)

FordGT90Concept said:


> JLabel <- Just display a message
> JTextArea <- Multiline text input
> JTextField <- Single line text input
> 
> ...



oh yes we learned that stuff. i can create buttons and fields and manipulate them. the problem is i cannot get a String into a JFrame. so if


```
String inputString;
System.out.println("Enter Secret Word: ");
inputString = keyboard.readLine();
```

i need to get inputString into a JFrame, specifically my southPanel...


```
JPanel southPanel = new JPanel();
southPanel.add(inputString);
getContentPane().add(southPanel, "South");
```

and it says the method add(Component) for type Container is not applicable for the arguments (String)


----------



## FordGT90Concept (Oct 15, 2009)

JPanel is just a Container for other Components.  TextField is a Component which primarily contains a String.

JFrame -- has a -> JPanel -- has a -> TextField -- has a -> String

Work backwards...

Create: TextField
Value: String

Create: JPanel
Value: TextField

Create: JFrame
Value: JPanel


----------



## Kreij (Oct 15, 2009)

Since I'm learning along with Rhino ...  something like this?

```
JTextField intputStringContainer = new JTextField(inputString)
JPanel panel = new JPanel();
panel.add(intputStringContainer);
```

For what I can garner from Rhino's description, it looks like he wants to display the input string hidden (masked). Since JTextField is an editable control, wouldn't a JLabel be a more likely candidate so it could not be edited in the GUI?
Or does JTextField have some kind of ReadOnly property?

Or am I completely off base here?


----------



## Easy Rhino (Oct 15, 2009)

Kreij said:


> Since I'm learning along with Rhino ...  something like this?
> 
> ```
> JTextField intputStringContainer = new JTextField(inputString)
> ...



you are right that in this case we need a JLabel to display our masked/unmasked word.
ive actually have it set up as you do but it doesnt display anything. im thinking it is because i am entering the word in the console. that is how my prof set it up tho. he actually used a dialog box.


----------



## Easy Rhino (Oct 15, 2009)

i think where most of my confusion lays is with JFrames and Strings. 

Is it possible to enter a word into the console and have it appear in a GUI ?

The only way you can enter and store a word from the console is by using a String. 

The only way you can put data onto a GUI is by using a JFrame. 

This is where I am stuck.


----------



## Kreij (Oct 16, 2009)

Why not have them enter it in the GUI?


----------



## Easy Rhino (Oct 16, 2009)

Kreij said:


> Why not have them enter it in the GUI?



well i am thinking that. the problem there is that JBbuttons/labels are all final. they do not change. So you can't put a label in the GUI that says "Enter Secret Word" and then have that same label change to "Guess A Letter."


----------



## Kreij (Oct 16, 2009)

Why do the two have to be in the same place?
2 labels, 2 input boxes


----------



## FordGT90Concept (Oct 16, 2009)

```
public class Program
{
	public static String UserInput = ""

	public static void main(String[] args)
	{
		System.out.println("Enter Word: ");
		UserInput = keyboard.readLine();

		// Call up the Main frame of the GUI.
		new Main();
	}
}

public class Main extends JFrame
{
	public Main()
	{
		// Set generics.
		this.setTitle("Test");
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		this.setSize(700, 300);
		this.setResizable(false);
		
		JPanel panel = new JPanel() // The panel.
		panel.add(new JLabel(Program.UserInput))  // The label set to the user inputed text.
		this.add(panel);
		
		this.setVisible(true);
	}
}
```
I didn't compile it so I'm not certain it works.




Easy Rhino said:


> well i am thinking that. the problem there is that JBbuttons/labels are all final. they do not change. So you can't put a label in the GUI that says "Enter Secret Word" and then have that same label change to "Guess A Letter."


You can change the text on JButton and JLabel via .setText("new value")


Generally speaking, you either want all console or all GUI.  They are like oil and water (due to the static nature of the console) so they don't mix well.


----------



## Easy Rhino (Oct 16, 2009)

FordGT90Concept said:


> ```
> public class Program
> {
> public static String UserInput = ""
> ...



well i am a noob. i just realized the JLabel guessLetter wasnt putting out inputString because there is no value for inputString yet when I declare JLabel.  

java -->    <-- me


----------



## Kreij (Oct 16, 2009)

Welcome to programming. If you read my thread on the Control array problem, you will realize stuff like this happens for the rest of your life. 
Get used to it.


----------



## Easy Rhino (Oct 16, 2009)

i have finally reached the HEART of my problem. check out my code...


```
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class TimeBomb extends JFrame implements ActionListener
{
	String inputString;
	String inputMask = "*";//mask
	private final BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
	
	private final JTextField tfInput = new JTextField(2);
	private final JLabel lblMessage = new JLabel("Enter A Letter: ");
	private final JLabel guessLetter = new JLabel(inputMask);
	private final JButton btnOK = new JButton("OK");
	private final JLabel timer = new JLabel("*-----");
	
	public TimeBomb() throws IOException//constructor for GUI
	{
		super("Time Bomb Game");
		
		System.out.println("Enter Secret Word: ");//enter secret word into console
		inputString = keyboard.readLine();//store secret word
		for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
			System.out.print(inputMask);//creates a mask of the secret word of the appropriate length

		Font f1 = new Font("Dialog", Font.PLAIN, 24);//set main font
		Font f2 = new Font("Dialog", Font.PLAIN, 32);//set larger font
		lblMessage.setFont(f1);
		tfInput.setFont(f1);
		guessLetter.setFont(f1);
		btnOK.setFont(f1);
		timer.setFont(f2);
		
		getContentPane().setLayout(new BorderLayout(1,1));

		JPanel northPanel = new JPanel();
		northPanel.add(lblMessage);
		getContentPane().add(northPanel, "North");
		
		JPanel westPanel = new JPanel();
		westPanel.add(timer);
		getContentPane().add(westPanel, "West");
		
		JPanel centerPanel = new JPanel();
		centerPanel.add(tfInput);
		getContentPane().add(centerPanel, "Center");
		
		JPanel eastPanel = new JPanel();
		eastPanel.add(btnOK);
		getContentPane().add(eastPanel, "East");
		btnOK.addActionListener(this);
		
		JPanel southPanel = new JPanel();
		southPanel.add(guessLetter);
		getContentPane().add(southPanel, "South");
		
		setSize(310, 200);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))//OK button gets entered letter and puts it in the south panel
		{
			guessLetter.setText(tfInput.getText());
		}
	}
	
	public static void main(String[] args) throws IOException
	{
		new TimeBomb();
	}
}//end TimeBomb class
```

notice...

private final JLabel guessLetter = new JLabel(inputMask);

well that is actually pulling the initial value of inputMask which is set to * as a class level variable. in the actual contsructor though, inputMask gets set to whatever the length of the word is. 

so i need to get guessLetter to read the inputMask from the contsructor, not from the class level variable.


----------



## FordGT90Concept (Oct 16, 2009)

```
String inputString;
	String inputMask = "*";//mask
```
Those two should have an access modifier on them.



```
private final JLabel guessLetter = new JLabel(inputMask);
```
That could raise an error because of the "final" flag.


----------



## Kreij (Oct 16, 2009)

final in Java is like const in C#, isn't it.
Does all that stuff have to be final?


----------



## FordGT90Concept (Oct 16, 2009)

It's the same as "readonly."

None of it has to be "final."


----------



## Easy Rhino (Oct 16, 2009)

FordGT90Concept said:


> It's the same as "readonly."
> 
> None of it has to be "final."



i took away final and still wouldnt work


----------



## FordGT90Concept (Oct 16, 2009)

I guess I don't understand what problem you are having.


----------



## Easy Rhino (Oct 16, 2009)

FordGT90Concept said:


> I guess I don't understand what problem you are having.



eheh. well the problem is that JLabel guessLetter = new JLabel(inputMask) is getting the inputMask value from the class level variable rather than from the constructor which sets inputMask to the length of the inputString but with * instead of letters. 

could this be an issue of the order of my code?


----------



## FordGT90Concept (Oct 16, 2009)

Well, this bit of code is quite useless:

```
for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
			System.out.print(inputMask);//creates a mask of the secret word of the appropriate length
```
System.out will do ***** in the console, not your JLabel.

guessLetter will be a JLabel with the text "*" on load.  You aren't chaning the value of it until the action is performed.


----------



## Easy Rhino (Oct 16, 2009)

FordGT90Concept said:


> Well, this bit of code is quite useless:
> 
> ```
> for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
> ...



that is my issue. i know that it will output ****in the console and i need it to output**** in guessLetter


----------



## FordGT90Concept (Oct 16, 2009)

```
String temp = "";
		for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
			temp +=  inputMask;//creates a mask of the secret word of the appropriate length
		guessLetter = new JLabel(temp);
```


----------



## Easy Rhino (Oct 16, 2009)

FordGT90Concept said:


> ```
> String temp = "";
> for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
> temp +=  inputMask;//creates a mask of the secret word of the appropriate length
> ...



i dont know where i would be without your help. do you have a paypal account? i need to buy you a beer.


----------



## Kreij (Oct 16, 2009)

If you get it, let me know and then send me yours too.
I'll buy you both a beer.
Ford for being a great help to everyone and you for your diligence and patience when learning how to code.


----------



## Easy Rhino (Oct 16, 2009)

Kreij said:


> If you get it, let me know and then send me yours too.
> I'll buy you both a beer.
> Ford for being a great help to everyone and you for your diligence and patience when learning how to code.



honestly i dont want to come off as a pain in the ass and i dont want anyone to think im taking their help for granted.


----------



## Kreij (Oct 16, 2009)

Don't flatter yourself. If we didn't want to help we wouldn't.  

I can only speak for myself as a coder, but perhaps Ford is the same.
I can't resist helping people if they need it. Just the way I am.


----------



## Easy Rhino (Oct 16, 2009)

Kreij said:


> Don't flatter yourself. If we didn't want to help we wouldn't.



oh i know! 

now my next challenge is to break down inputString into an array and have it store the values of each character so that i can compare the input entered into JtextField tfInput with that of the secret word. i know how to create a string array but im not sure how to create an array that a user would input.


----------



## Easy Rhino (Oct 16, 2009)

now i can do this...


```
import java.io.*;

public class ArrayDemo2 
{
	String inputString, secretWord;
	
	private BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
	
	public void wordInput() throws IOException
	{
		System.out.println("Enter Word: ");
		inputString = keyboard.readLine();

		String secretWord = (inputString);
			System.out.print(secretWord.charAt(5));
	}
	
	public static void main(String[] args) throws IOException
	{
		ArrayDemo2 x = new ArrayDemo2();
		x.wordInput();

	}//end of main
}//end of class
```

and it will output the letter from the 5th indices (it starts at 0 if you didnt know).


----------



## Kreij (Oct 16, 2009)

I'm not sure how you want to go about it, but you should not have to break the input string down into a character array. You can find out if a chatacter exists in the string by using the string.IndexOf() method.

This returns the first instance of the character in the string. To check if there are more of the same character (eg. "mississippi" lol), re-run the method starting at the index just after the last found occurance. Repeat until it returns no matches.

Each time you get an possitive match on an index, show the character in the "mask" string at the same index.


----------



## FordGT90Concept (Oct 16, 2009)

Just do:

byte[] secret = inputString.getBytes();


You need to do the same with the user text:
byte[] user = keyboard.readLine().getBytes();


Compare the two:


```
private static byte[] CompareSecret(byte[] secret, byte[] user)
{
  if (secret.getLength() == user.getLength())
  {
    byte[] output = new byte[secret.getLength()];
    for (int i = 0; i < secret.getLength(); i++)
    {
      if (secret[i] == user[i])
        output[i] = secret[i];
      else
        output[i] = 42; // *
    }
    return output;
  }
  else
  {
    return null; // invalid
  }
}
```


Turn the result back into a string:

txtDisplay.setText(new String(CompareSecret(secret, user)));



@Kreij:
Array.IndexOf is much slower than going through the entire array once.


----------



## Kreij (Oct 16, 2009)

Why go to that length, Ford, the string is already a character array by definition?
Why not just use the existing methods to pick out what you want?
Am I missing something?


----------



## FordGT90Concept (Oct 16, 2009)

Strings are not composed of an array of char like in .NET.  This is why you have to use String.charAt(i) rather than String_.  Strings are constant (note how .charAt has no "set" equivilent).  If you break it down to an array of bytes, you can change any index at any time so long as it is inside the constraints of the array (as one would expect).  Loop through that array once and you're done.

Additionally, String is UTF-16, not ASCII.  new String(byte[]) automatically makes the conversion.  Not that it really matters but the byte array is half the size of String equivilent (smaller memory footprint and faster to work with)._


----------



## Kreij (Oct 16, 2009)

> Strings are constant



#region Start Rant

Good Lord, does Sun hold millions of shares of keyboard repair stock?
No wonder the source code for a simple Java program lists code like an unabridged dictionary.

I understand the need for the cross-platform compatibility, but non-mutable strings?!! 

In ER's code, he imports all of the controls (Jpanel, JButton, etc.) individually as namespaces (packages?).
Why are they not all in one package? (or namespace or whatever)
It would be like having to do..

```
using System.Windows.Panel;
using System.Windows.Label;
using System.Windows.ComboBox;
using etc. etc. etc.
```

Arrrrgh.
Okay, I am officially going back to C#.
(of course, I will still help ER with his code  as the languages are pretty close syntacticaly. )

# endregion


----------



## FordGT90Concept (Oct 16, 2009)

That's why C# is murdering Java for Windows developement.  JRT was just thrown together with little consideration given to common sense (you don't friggen "swing" to make a "window" or "awt" to handle the "console").

We need not mention how much faster and thorough .NET is as well.


----------



## Easy Rhino (Oct 19, 2009)

FordGT90Concept said:


> Just do:
> 
> byte[] secret = inputString.getBytes();
> 
> ...



thanks. 2 things. with the data type byte you use .length not getLength()

also, im adding that method to the main method for execution and i am getting...

the method CompareSecret(byte[] byte[])  in the type TimeBomb is not applicable for the argument (byte, byte)

i think it may be how i have my code arranged because it also says that for the settext method.


```
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class TimeBomb extends JFrame implements ActionListener
{
	public String inputString;
	public String inputMask = "*";//mask
	public String temp = "";
	public static byte user, secret;
	
	BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
	
	JTextField tfInput = new JTextField(2);
	JLabel lblMessage = new JLabel("Enter A Letter: ");
	JLabel guessLetter = new JLabel();
	JButton btnOK = new JButton("OK");
	JLabel timer = new JLabel("*-----");
	
	public TimeBomb() throws IOException//constructor for GUI
	{
		super("Time Bomb Game");
		
		//secret word
		System.out.println("Enter Secret Word: ");//enter secret word into console
		inputString = keyboard.readLine();//store secret word
		for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
			temp +=  inputMask;//creates a mask of the secret word of the appropriate length
			guessLetter = new JLabel(temp);

		byte[] secret = inputString.getBytes();
		byte[] user = keyboard.readLine().getBytes();
			
		//set font
		Font f1 = new Font("Dialog", Font.PLAIN, 24);//set main font
		Font f2 = new Font("Dialog", Font.PLAIN, 32);//set larger font
		lblMessage.setFont(f1);
		tfInput.setFont(f1);
		guessLetter.setFont(f1);
		btnOK.setFont(f1);
		timer.setFont(f2);
		
		//gui properties
		getContentPane().setLayout(new BorderLayout(1,1));

		JPanel northPanel = new JPanel();
		northPanel.add(lblMessage);
		getContentPane().add(northPanel, "North");
		
		JPanel westPanel = new JPanel();
		westPanel.add(timer);
		getContentPane().add(westPanel, "West");
		
		JPanel centerPanel = new JPanel();
		centerPanel.add(tfInput);
		getContentPane().add(centerPanel, "Center");
		
		JPanel eastPanel = new JPanel();
		eastPanel.add(btnOK);
		getContentPane().add(eastPanel, "East");
		btnOK.addActionListener(this);
		
		JPanel southPanel = new JPanel();
		southPanel.add(guessLetter);
		getContentPane().add(southPanel, "South");
		
		setSize(310, 200);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	private byte[] CompareSecret(byte[] secret, final byte[] user)
	{
	  if (secret.length == user.length)
	  {
	    byte[] output = new byte[secret.length];
	    for (int i = 0; i < secret.length; i++)
	    {
	      if (secret[i] == user[i])
	        output[i] = secret[i];
	      else
	        output[i] = 42; // *
	    }
	    return output;
	  }
	  else
	  {
	    return null; // invalid
	  }
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))//OK button gets entered letter and puts it in the south panel
		{
				guessLetter.setText(tfInput.getText());
		}
	}
	
	public static void main(String[] args) throws IOException
	{
		TimeBomb x = new TimeBomb();
		x.CompareSecret(secret, user);
	}
}//end TimeBomb class
```


----------



## FordGT90Concept (Oct 19, 2009)

Easy Rhino said:


> thanks. 2 things. with the data type byte you use .length not getLength()


It's been a long time since I coded Java so take everything I say as pseudocode. XD




Easy Rhino said:


> the method CompareSecret(byte[] byte[])  in the type TimeBomb is not applicable for the argument (byte, byte)


Make sure you are handing CompareSecret arrays of bytes not just a single byte as defined here:

```
public static byte user, secret;
```


----------



## Easy Rhino (Oct 19, 2009)

FordGT90Concept said:


> It's been a long time since I coded Java so take everything I say as pseudocode. XD




you -->  <-- me



> Make sure you are handing CompareSecret arrays of bytes not just a single byte as defined here:
> 
> ```
> public static byte user, secret;
> ```



yea that fixed it. when i run the program i enter the word and i have to hit enter twice in the console. im guessing it is because im simply not done tweaking the program. however, the user and secret byte arrays say they are never read locally. i have them in the TimeBomb constructor. also, im a little confused with how to properly get the user guessed letter from the GUI onto the GUI if it is correct, and if it isnt to not display but instead take a tick off the timebomb counter. 



for the first, i think i need to rework my ActionPerformed(ActionEvent e) method. with this line...


```
txtDisplay.setText(new String(CompareSecret(secret, user)));
```

would i make txtDisplay a JFrame? obviously the compareSecret method is doing all the actual work in comparing the arrays but outputting the data has me perplexed. i know the simple setText and getText methods work in this instance but im not sure how. i cant add a new JPanel to this GUI setup so I have to somehow replace guessLetter with txtDisplay.


----------



## FordGT90Concept (Oct 19, 2009)

JLabel or a readonly JTextField work well for displaying strings.  The way you have it written (using new String) will work to turn the bytes back into text.


----------



## Easy Rhino (Oct 19, 2009)

FordGT90Concept said:


> JLabel or a readonly JTextField work well for displaying strings.  The way you have it written (using new String) will work to turn the bytes back into text.



yes, but get the problem is you cant create any more JPanels. you can only have a north, south, east, center and west. i may have to look into this.


----------



## FordGT90Concept (Oct 19, 2009)

There's different kinds of Layout types that can put in a JFrame allowing you to add multiple controls to it.  I used GridBagLayout a lot, for example.


----------



## Easy Rhino (Oct 19, 2009)

FordGT90Concept said:


> There's different kinds of Layout types that can put in a JFrame allowing you to add multiple controls to it.  I used GridBagLayout a lot, for example.



yup i gave that a try. you think it will be easier to work with?


----------



## FordGT90Concept (Oct 19, 2009)

You'll just have to find that right layout for what you are looking to achieve.  This describes them all:
http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html


----------



## Easy Rhino (Oct 20, 2009)

hrm, my prof was able to run the program using BorderLayout. when he guessed a letter correctly that letter replaces the mask * so he didnt need to use any other layout. hrm...


----------



## FordGT90Concept (Oct 20, 2009)

Then just replace the text in the field that is currently displaying the mask.


----------



## Easy Rhino (Oct 21, 2009)

FordGT90Concept said:


> Then just replace the text in the field that is currently displaying the mask.



i figured out that i could add as many things to panes as necessary so i wont have to change the entire gui layout. yay me.

so you are saying that i should be able to take the tfInput that the user enters into the textfield and if it is correct it should simply replace the mask of that letter?


----------



## FordGT90Concept (Oct 21, 2009)

I can't advise without knowing what I'm looking at it.  Screenshot, please?


----------



## Easy Rhino (Oct 21, 2009)

FordGT90Concept said:


> I can't advise without knowing what I'm looking at it.  Screenshot, please?




```
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class TimeBomb extends JFrame implements ActionListener
{
	public String inputString;
	public String inputMask = "*";//mask
	public String temp = "";
	public static byte[] user, secret;
	
	BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
	
	JTextField tfInput = new JTextField(2);
	JLabel lblMessage = new JLabel("Guess A Letter: ");
	JLabel guessLetter = new JLabel();
	JButton btnOK = new JButton("OK");
	JLabel timer = new JLabel("*-----");
	
	public TimeBomb() throws IOException//constructor for GUI
	{
		super("Time Bomb Game");
		
		//secret word
		System.out.println("Enter Secret Word: ");//enter secret word into console
		inputString = keyboard.readLine();//store secret word
		for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
			temp +=  inputMask;//creates a mask of the secret word of the appropriate length
			guessLetter = new JLabel(temp);

		byte[] secret = inputString.getBytes();//convert secret word String into byte array
		byte[] user = keyboard.readLine().getBytes();
			
		//set font
		Font f1 = new Font("Dialog", Font.PLAIN, 24);//set main font
		Font f2 = new Font("Dialog", Font.PLAIN, 32);//set larger font
		lblMessage.setFont(f1);
		tfInput.setFont(f1);
		guessLetter.setFont(f1);
		btnOK.setFont(f1);
		timer.setFont(f2);
		
		//gui properties
		getContentPane().setLayout(new BorderLayout(1,1));

		JPanel northPanel = new JPanel();
		northPanel.add(lblMessage);
		northPanel.add(tfInput);
		northPanel.add(btnOK);
		btnOK.addActionListener(this);
		getContentPane().add(northPanel, "North");
	
		JPanel centerPanel = new JPanel();
		centerPanel.add(guessLetter);
		getContentPane().add(centerPanel, "Center");
		
		JPanel southPanel = new JPanel();
		southPanel.add(timer);
		getContentPane().add(southPanel, "South");
		
		setSize(310, 200);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	private byte[] CompareSecret(byte[] secret, final byte[] user)
	{
	  if (secret.length == user.length)
	  {
	    byte[] output = new byte[secret.length];
	    for (int i = 0; i < secret.length; i++)
	    {
	      if (secret[i] == user[i])
	        output[i] = secret[i];
	      else
	        output[i] = 42; // *
	    }
	    return output;
	  }
	  else
	  {
	    return null; // invalid
	  }
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))//OK button gets entered letter and puts it in the south panel
		{
			guessLetter.setText(tfInput.getText());
		//	txtDisplay.setText(new String(CompareSecret(secret, user)));
		}
	}
	
	public static void main(String[] args) throws IOException
	{
		TimeBomb x = new TimeBomb();
		x.CompareSecret(secret, user);
	}
}//end TimeBomb class
```


----------



## FordGT90Concept (Oct 21, 2009)

Where it was ****** and turned to s, it should show "s*****" or whatever is correct.  Unless you are using that space to show what was previously used?

What's the one on the bottom for ( * _ _ _ _ _ )?


----------



## Easy Rhino (Oct 21, 2009)

FordGT90Concept said:


> Where it was ****** and turned to s, it should show "s*****" or whatever is correct.  Unless you are using that space to show what was previously used?
> 
> What's the one on the bottom for ( * _ _ _ _ _ )?



yea when it is ****** and i enter s in the txtfield it should read s*****

and *----- is the timer. so if you get 1 wrong it will be *---- and two wrong *--- until you get to just * and then it will have to say BOOM!


----------



## FordGT90Concept (Oct 21, 2009)

Ah, so use CompareSecret before you display it.  That's exactly what it is for.


----------



## Easy Rhino (Oct 21, 2009)

FordGT90Concept said:


> Ah, so use CompareSecret before you display it.  That's exactly what it is for.



well i understand comparesecret does all the work but i dont understand how to use it before i display it. for instance, in my code it says that both 


```
byte[] secret = inputString.getBytes();//convert secret word String into byte array
		byte[] user = keyboard.readLine().getBytes();
```

are never read locally. could it be that i am not utilizing these two arrays correctly?


----------



## FordGT90Concept (Oct 21, 2009)

Are you ever using CompareSecrets?  keyboard.readLine() would only work in the console.  If you are inputting text through that button, the button should get the bytes, run it through CompareSecrets, and update the label.


----------



## Easy Rhino (Oct 21, 2009)

FordGT90Concept said:


> Are you ever using CompareSecrets?  keyboard.readLine() would only work in the console.  If you are inputting text through that button, the button should get the bytes, run it through CompareSecrets, and update the label.



well i think so. lol. check out my code!


----------



## Easy Rhino (Oct 21, 2009)

i spent time reworking my code. one of the project rules is that you cant show the secret word which sort of means you cant use the console. so im using JOptionPane. not a big change but i will have to rework some code. regardless it will be a lot cleaner in the end. also, i think i have located the problem when the GUI actually executes after i enter the secret word i get 

Exception in thread "main" java.lang.NullPointerException
	at TimeBomb.CompareSecret(TimeBomb.java:86)
	at TimeBomb.main(TimeBomb.java:117)

which as you can see points to the CompareSecret method. 

currently i have the array that breaks inputString down into a byte array. now i need a for it to read the input from the user textfield and check it against the inputString. i know that is what the compareSecret is for but this is clearly where my problem is in discovering the solution. isnt the compareSecret method actually just checking to see if the words are the same length? instead of matching characters it expects a full word input? i need to somehow break the inputString down into an array that can be checked against the letter the user inputs into the textfield. 


NOTE: the lines that are commented are there to remind me of the changes.


```
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import java.io.IOException;

public class TimeBomb extends JFrame implements ActionListener
{
	public String inputString;
	public String inputMask = "*";//mask
	public String temp = "";
	public static byte[] user, secret;
	
	JTextField tfInput = new JTextField(2);
	JLabel lblMessage = new JLabel("Guess A Letter: ");
	JLabel maskedWord = new JLabel();
	JLabel guessedLetter = new JLabel();
	JButton btnOK = new JButton("OK");
	JLabel timer = new JLabel("*-----");
	
	//BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));	
	
	public TimeBomb() //constructor for GUI
	{
		super("Time Bomb Game");
		
		//secret word
		inputString = JOptionPane.showInputDialog("Enter Secret Word: ");
	//	inputString = keyboard.readLine();
	//	System.out.println("Enter Secret Word: ");//enter secret word into console
	//	inputString = keyboard.readLine();//store secret word
		for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
			temp +=  inputMask;//creates a mask of the secret word of the appropriate length
			maskedWord = new JLabel(temp);

		byte[] secret = inputString.getBytes();//convert secret word String into byte array
	//	byte[] user = keyboard.readLine().getBytes();
		
		//set font
		Font f1 = new Font("Dialog", Font.PLAIN, 24);//set main font
		Font f2 = new Font("Dialog", Font.PLAIN, 32);//set larger font
		lblMessage.setFont(f1);
		tfInput.setFont(f1);
		guessedLetter.setFont(f1);
		btnOK.setFont(f1);
		timer.setFont(f2);
		maskedWord.setFont(f1);
		
		//gui properties
		getContentPane().setLayout(new BorderLayout(1,1));

		JPanel northPanel = new JPanel();
		northPanel.add(lblMessage);
		northPanel.add(tfInput);
		northPanel.add(btnOK);
		btnOK.addActionListener(this);
		getContentPane().add(northPanel, "North");
	
		JPanel centerPanel = new JPanel();
		centerPanel.add(maskedWord);
		centerPanel.add(guessedLetter);
		getContentPane().add(centerPanel, "Center");
		
		JPanel southPanel = new JPanel();
		southPanel.add(timer);
		getContentPane().add(southPanel, "South");
		
		setSize(350, 200);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	private byte[] CompareSecret(byte[] secret, final byte[] user)
	{
	  if (secret.length == user.length)
	  {
	    byte[] output = new byte[secret.length];
	    for (int i = 0; i < secret.length; i++)
	    {
	      if (secret[i] == user[i])
	        output[i] = secret[i];
	      else
	        output[i] = 42; // *
	    }
	    return output;
	  }
	  else
	  {
	    return null; // invalid
	  }
	}

	
	public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))//OK button gets entered letter and puts it in the south panel
		{
			guessedLetter.setText(tfInput.getText());
		//	txtDisplay.setText(new String(CompareSecret(secret, user)));
		}
	}
	
	public static void main(String[] args) 
	{
		TimeBomb x = new TimeBomb();
		x.CompareSecret(secret, user);
	}
}//end TimeBomb class
```


----------



## FordGT90Concept (Oct 21, 2009)

Easy Rhino said:


> Exception in thread "main" java.lang.NullPointerException
> at TimeBomb.CompareSecret(TimeBomb.java:86)
> at TimeBomb.main(TimeBomb.java:117)


The error numbers don't line up with the code you pasted so I can't help there.




Easy Rhino said:


> currently i have the array that breaks inputString down into a byte array. now i need a for it to read the input from the user textfield and check it against the inputString. i know that is what the compareSecret is for but this is clearly where my problem is in discovering the solution. isnt the compareSecret method actually just checking to see if the words are the same length? instead of matching characters it expects a full word input? i need to somehow break the inputString down into an array that can be checked against the letter the user inputs into the textfield.


CompareSecret makes sure the two match in length.  It should/would error if they weren't.  If they match, it loops through them both comparing letter by letter.  If it is a match, it outputs the letter.  If it doesn't match, it outputs an astrisk (*).

Wait a minute, they only guess one letter at a time?


----------



## Easy Rhino (Oct 21, 2009)

FordGT90Concept said:


> The error numbers don't line up with the code you pasted so I can't help there.
> 
> 
> 
> ...



yes. sorry that is my fault. ive continued to rework the code and i think i am getting there. i break down inputString into a byte array now i need to compare the letter entered into the textfield with the inputString byte array to see if the letter matches any in the inputString array. if there is a match then print the letter onthe GUI in the correct spot in the masked array. if it is wrong deduct one dash from the timer.


```
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class TimeBomb extends JFrame implements ActionListener
{
	public String inputString;
	public String inputMask = "*";//mask
	public String temp = "";
	public static byte[] user, secret;
	
	JTextField tfInput = new JTextField(2);
	JLabel lblMessage = new JLabel("Guess A Letter: ");
	JLabel maskedWord = new JLabel();
	JLabel guessedLetter = new JLabel();
	JButton btnOK = new JButton("OK");
	JLabel timer = new JLabel("*-----");
	
	public TimeBomb() //constructor for GUI
	{
		super("Time Bomb Game");
		
		//secret word
		inputString = JOptionPane.showInputDialog("Enter Secret Word: ");

		for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
			temp +=  inputMask;//creates a mask of the secret word of the appropriate length
			maskedWord = new JLabel(temp);

		byte[] secret = inputString.getBytes();//convert secret word String into byte array
		
		//set font
		Font f1 = new Font("Dialog", Font.PLAIN, 24);//set main font
		Font f2 = new Font("Dialog", Font.PLAIN, 32);//set larger font
		lblMessage.setFont(f1);
		tfInput.setFont(f1);
		guessedLetter.setFont(f1);
		btnOK.setFont(f1);
		timer.setFont(f2);
		maskedWord.setFont(f1);
		
		//gui properties
		getContentPane().setLayout(new BorderLayout(1,1));

		JPanel northPanel = new JPanel();
		northPanel.add(lblMessage);
		northPanel.add(tfInput);
		northPanel.add(btnOK);
		btnOK.addActionListener(this);
		getContentPane().add(northPanel, "North");
	
		JPanel centerPanel = new JPanel();
		centerPanel.add(maskedWord);
		centerPanel.add(guessedLetter);
		getContentPane().add(centerPanel, "Center");
		
		JPanel southPanel = new JPanel();
		southPanel.add(timer);
		getContentPane().add(southPanel, "South");
		
		setSize(350, 200);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	private byte[] CompareSecret(byte[] secret, final byte[] user)
	{
	  if (secret.length == user.length)
	  {
	    byte[] output = new byte[secret.length];
	    for (int i = 0; i < secret.length; i++)
	    {
	      if (secret[i] == user[i])
	        output[i] = secret[i];
	      else
	        output[i] = 42; // *
	    }
	    return output;
	  }
	  else
	  {
	    return null; // invalid
	  }
	}

	
	public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))//OK button gets entered letter and puts it in the south panel
		{
			CompareSecret(secret, user);
		}
	}
	
	public static void main(String[] args) 
	{
		new TimeBomb();
	}
}//end TimeBomb class
```


----------



## FordGT90Concept (Oct 21, 2009)

I made a console app quick to try what you are doing.  Here's the magic maker:

```
private static string _Secret = "";
        private static string _Reveal = "";
        private const char MASK = '*';

        // Make sure _Reveal is all MASK before calling Magic (e.g. _Secret = "blamo", _Reveal = "*****")

        private static bool Magic(char letter)
        {
            bool hit = false; // True for a hit, false for no hit.

            string temp = ""; // We are going to be reading from _Reveal so we can't write to it.
            for (int i = 0; i < _Secret.Length; i++) // Loop through _Secret and _Reveal --length must match
            {
                if (_Reveal[i] == MASK) // Does this character in _Reveal match the mask?
                {
                    if (letter == _Secret[i])  // Yes, but does the letter match?
                    {
                        temp += _Secret[i];  // Yes, add the new letter to the soon-to-be mask.
                        hit = true;  // Don't reduce the clock on the user for this one.
                    }
                    else
                        temp += MASK; // They guessed wrong for this character.
                }
                else
                    temp += _Reveal[i]; // This one is already correct.
            }
            _Reveal = temp; // copy our updated _Reveal to the _Reveal variable

            return hit;  // Return with whether or not the user needs to be slapped
        }
```
This function supercedes CompareSecret.


----------



## Easy Rhino (Oct 21, 2009)

FordGT90Concept said:


> I made a console app quick to try what you are doing.  Here's the magic maker:
> 
> ```
> private static string _Secret = "";
> ...



how do you get the input from the textfield tho?


----------



## Easy Rhino (Oct 21, 2009)

for _Secret_ and _Reveal it says the type of expression must be an array but it resolved to a string. and for MASK it says it cannot make a static reference to a nonstatic field. didnt you say something about replacing  with a method? i think you edited your post and erased that comment.

also, im guessing i do not want to create a byte array for inputString? i think i am more confused now so i am going to bed. 

but first, all i really need to do is break inputString down into an array that can be used to check against the letter guessed by the user in JTextField. 
do i do this with a character array instead of a byte array?

if the letter matches any indices of the inputString array then  replace the mask in that array indices with the letter. 

if not then do nothing BUT reduced one from the counter._


----------



## FordGT90Concept (Oct 21, 2009)

Easy Rhino said:


> how do you get the input from the textfield tho?


TextField.getText();




Easy Rhino said:


> for _Secret_ and _Reveal it says the type of expression must be an array but it resolved to a string. and for MASK it says it cannot make a static reference to a nonstatic field. didnt you say something about replacing  with a method? i think you edited your post and erased that comment._


_
You'll need to use .getChar(i) instead of .

MASK should be constant but it doesn't have to be.  Const naturally means static.  It is only static in my example because I did the whole thing in a console._


----------



## Easy Rhino (Oct 21, 2009)

FordGT90Concept said:


> TextField.getText();
> 
> 
> 
> ...


_

i think you mean charAt(i) because .getChars(i) doesnt work in this instance. 

so then i need to create a character array from the user word rather than a byte array?

this info seems to be what i am aiming at

http://java.sun.com/docs/books/tutorial/java/data/strings.html

ok i think ive worked through the code now i just need to have it actually execute when i hit the OK button._


----------



## Easy Rhino (Oct 21, 2009)

aha! ok i think ive written some good code here. 


```
inputString = JOptionPane.showInputDialog("Enter Secret Word: ");//user enters secret word

		for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
			temp +=  inputMask;//creates a mask of the secret word of the appropriate length
			maskedWord = new JLabel(temp);

		int len = inputString.length();//gets the length of the secret word and stores it in len
		char[] secretWordArray = new char[len];//create array using len
		
		for(int i = 0; i < len; i++)
		{
			secretWordArray[i] = inputString.charAt(i);//populate array using inputString
		}

                textfieldString = tfInput.getText();
		int len2 = textfieldString.length();
		char[] letterArray = new char[len2];
		
		for(int j = 0; j < len2; j++)
		{
			letterArray[j] = textfieldString.charAt(j);
		}
```

as yuo can see it turns inputString into a char array! and it turns the letter enetered into the textfield into an array!!!!!! now i need to compare these two!

btw: you do know that you dont have to guess the letters in order. meaning if the secret word is awesome you can guess 's' and it will put s in the proper spot. if you guess 'e' it will reveal BOTH 'e's


----------



## FordGT90Concept (Oct 21, 2009)

Easy Rhino said:


> btw: you do know that you dont have to guess the letters in order. meaning if the secret word is awesome you can guess 's' and it will put s in the proper spot. if you guess 'e' it will reveal BOTH 'e's


That's what my "Magic" method did.


----------



## Easy Rhino (Oct 21, 2009)

FordGT90Concept said:


> That's what my "Magic" method did.



k i guess im just having issues manipulating it. also, when i press the OK button what should the command look like to actually get magic to work? cause i cant do any of the .getText methods on Magic.

blerg. we only spent 1 week on strings and 1 week on arrays. im not sure but i think i am confusing myself more. for instance, i dont know where _Secret, _Reveal or MASK actually come from.


----------



## FordGT90Concept (Oct 21, 2009)

You may want to handle the whole thing as a bytes instead of string/char.  C# handles strings much better than Java.

_Secret (string), _Reveal (string), and MASK (const char) are class level variables.  _Secret is where you stick the secret word (e.g. "blamo"), _Reveal is where you stick your string to display (initially, "*****" -- must always match _Secret in length), and MASK is used to create _Reveal and check if that character is a candidate to be updated.

You'll need to make some variables class-level like I did (_Secret and _Reveal).  You'll have to accept the character or byte with which to compare to secret/reveal.  Then you'll need to return whether or not it was a hit or a miss.

Inside your button, you need to do a two things:
1) Run Magic (or whatever you name it--that's a bad name) using your .getText from guess letter. ***
2) Using the returned value from Magic, update your timer.


*** Make sure the length of .getText is > 0 then use .charAt(0) to get the character or .getBytes()[0] to get the byte of the character.


----------



## Easy Rhino (Oct 21, 2009)

FordGT90Concept said:


> You may want to handle the whole thing as a bytes instead of string/char.  C# handles strings much better than Java.
> 
> You'll need to make some variables class-level like I did (secret and reveal).  You'll have to accept the character or byte with which to compare to secret/reveal.  Then you'll need to return whether or not it was a hit or a miss.
> 
> ...



well i have made the char arrays just fine from the inputString and the textField. look at this code...


```
inputString = JOptionPane.showInputDialog("Enter Secret Word: ");//user enters secret word

		for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
			temp +=  inputMask;//creates a mask of the secret word of the appropriate length
			maskedWord = new JLabel(temp);

		int len = inputString.length();//gets the length of the secret word and stores it in len
		char[] secretWordArray = new char[len];//create array using len
		
		for(int i = 0; i < len; i++)
		{
			secretWordArray[i] = inputString.charAt(i);//populate array using inputString
		}
		
		textfieldString = tfInput.getText();
		int len2 = textfieldString.length();
		char[] letterArray = new char[len2];
		
		for(int j = 0; j < len2; j++)
		{
			letterArray[j] = textfieldString.charAt(j);
		}
```

you see it creates a mask for inputString and creates a char array for inputString and the letter entered in the textfield jTextField. 

it should be fairly simple to scan the inputString array and if the letter entered in the JTextField matches any of the char in the array to replace the * from the mask with that letter. i should be able to use my already created class level variables to do this.


----------



## Easy Rhino (Oct 22, 2009)

to help me visual my problem i wrote up a little program that compares two Strings by breaking them down into char arrays and then printing if they match by using boolean. then i have an if statement setup to compare indices. i need to take that concept one step further and have an if statement that checks to see if the guessed letter is equal to any of the letters in the secret word. 
i thought something like 

if(secretWordArray_ == guessedLetter)

would do it but it only checks the first indices. 



		Code:
	

import java.util.Arrays;

import javax.swing.*;

public class anotherarraytest 
{
	String inputString1 = "";
	String inputString2 = "";
	int i,j;
	
	public anotherarraytest()
	{
		inputString1 = JOptionPane.showInputDialog("Enter Secret Word: ");
		
		int len1 = inputString1.length();
		char[] secretWordArray = new char[len1];
		for(int i = 0; i < len1; i++)
		{
			secretWordArray[i] = inputString1.charAt(i);
		}
		
		inputString2 = JOptionPane.showInputDialog("Guess Letter: ");
		
		int len2 = inputString2.length();
		char[] guessedLetter = new char[len2];
		for (int j = 0; j < len2; j++)
		{
            guessedLetter[j] = inputString2.charAt(j);
		}
		
		boolean result = Arrays.equals(secretWordArray, guessedLetter);
		System.out.println("Are they the same? " + result);
		System.out.println("Secret Word = " + inputString1);
		System.out.println("Guessed Letter = " + inputString2);
		
		if(secretWordArray[i] == guessedLetter[j])
		{
			System.out.println("You Got A Match! ");
		}
		else
		{
			System.out.println("No Match! ");
		}
		return;
    }

	public static void main(String[] args)
	{
		new anotherarraytest();
	}
		
}

_


----------



## FordGT90Concept (Oct 22, 2009)

You have to put that conditional in a loop so it increments i for each character in the string.


```
for (int i = 0; i < secretWordArray.length(); i++)
{
	if(secretWordArray[i] == guessedLetter[j])
	{
		System.out.println("You Got A Match! ");
	}
	else
	{
		System.out.println("No Match! ");
	}
}
```


----------



## Easy Rhino (Oct 22, 2009)

FordGT90Concept said:


> You have to put that conditional in a loop so it increments i for each character in the string.
> 
> 
> ```
> ...





you cant do .length() to an array but i just changed it to inputString1.length() in the for loop and it worked! 

and what is better i get a console readout of

Secret Word = secret
Guessed Letter = e
No Match! 
You Got A Match! 
No Match! 
No Match! 
You Got A Match! 
No Match! 

so it is working great! 

now i just need to get a mask to work somehow


----------



## FordGT90Concept (Oct 22, 2009)

Again, that Magic code does it and does it right.  You'll for sure need three strings (reveal, secret, and temp).  Secret can't be altered and reveal needs to be available to compare it to Secret so you need to put the results of the comparison in a third variable which is later used to update Reveal.


----------



## Easy Rhino (Oct 22, 2009)

sloooooooooooooow progress. hey ford, when you get a second could you look through my code. after i enter the secret word in JOptionPane it pulls up the GUI but then errors on 

if(secretWordArray_ == letterArray[j])

and says array index out of bounds exception. now i know that means it hit an indices out of its range but not sure why it happened. here is my code. 
note: i havnt set anything in actionEvent yet cause i have no idea what to put there to get the inputed letter to actually go into the mask.



		Code:
	

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class TimeBomb extends JFrame implements ActionListener
{
	public String inputString = "";
	public String textfieldString = "";
	public String inputMask = "*";//mask
	public String temp = "";
	int i,j;
	public char secretWordArray[], letterArray[];
	
	JTextField tfInput = new JTextField(2);
	JLabel lblMessage = new JLabel("Guess A Letter: ");
	JLabel maskedWord = new JLabel();
	JLabel guessedLetter = new JLabel();
	JButton btnOK = new JButton("OK");
	JLabel timer = new JLabel("*-----");
	
	public TimeBomb() //constructor for GUI
	{
		super("Time Bomb Game");
		
		inputString = JOptionPane.showInputDialog("Enter Secret Word: ");//user enters secret word
		int len = inputString.length();//gets the length of the secret word and stores it in len
		char[] secretWordArray = new char[len];//create array using len
		for(int i = 0; i < len; i++)
		{
			secretWordArray[i] = inputString.charAt(i);//populate array using inputString
		}
		for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
		{
			temp +=  inputMask;//creates a mask of the secret word of the appropriate length
			maskedWord = new JLabel(temp);
		}
		

		Font f1 = new Font("Dialog", Font.PLAIN, 24);//set main font
		Font f2 = new Font("Dialog", Font.PLAIN, 32);//set larger font
		lblMessage.setFont(f1);
		tfInput.setFont(f1);
		guessedLetter.setFont(f1);
		btnOK.setFont(f1);
		timer.setFont(f2);
		maskedWord.setFont(f1);
		
		getContentPane().setLayout(new BorderLayout(1,1));//simple gui layout

		JPanel northPanel = new JPanel();
		northPanel.add(lblMessage);
		northPanel.add(tfInput);
		northPanel.add(btnOK);
		btnOK.addActionListener(this);
		getContentPane().add(northPanel, "North");
	
		JPanel centerPanel = new JPanel();
		centerPanel.add(maskedWord);
		centerPanel.add(guessedLetter);
		getContentPane().add(centerPanel, "Center");
		
		JPanel southPanel = new JPanel();
		southPanel.add(timer);//count down to explosion
		getContentPane().add(southPanel, "South");
		
		setSize(350, 200);//should be large enough on all platforms
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		textfieldString = tfInput.getText();//string created from JTextField
		int len2 = textfieldString.length();//gets the length of the letter
		char[] letterArray = new char[len2];//creates array using len2
		for(int j = 0; j < len2; j++)
		{
			letterArray[j] = textfieldString.charAt(j);//populates array using textfieldString
		}
		
		for(int i = 0; i < inputString.length(); i++)
		{
			if(secretWordArray[i] == letterArray[j])
			{
				temp += textfieldString.charAt(i);
			}	
			else
			{
				temp += inputMask;
			}
		}
	}
	

	
	public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))//OK button gets entered letter and puts it in the south panel
		{
			
		}

	}
	
	public static void main(String[] args) 
	{
		new TimeBomb();
	}
}//end TimeBomb class

_


----------



## FordGT90Concept (Oct 22, 2009)

letterArray has only one char (containing "2").


----------



## Easy Rhino (Oct 22, 2009)

FordGT90Concept said:


> letterArray has only one char (containing "2").



strange because letterArray is populated using 

int len2 = textfieldString.length()

and textfieldString is a String that = tfInput.getText() and at that point it isnt populated at all.


----------



## Easy Rhino (Oct 22, 2009)

fixed that little issue. i had to move the letterArray and secretWordArray creation to the actionPerformed section. i also moved the if statement that compares the two arrays to the actionPerformed method. 

now i just need to get it to actually write the input letter to the mask which is hiding the secret word. for that i have...


```
for(int i = 0; i < inputString.length(); i++)
			{
				if(secretWordArray[i] == letterArray[j])
				{
					temp += textfieldString;
				}	
				else
				{
					temp += inputMask;
				}
			}
```

but when i hit the OK button nothing happens. maybe my code isnt actually changing the value??


```
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class TimeBomb extends JFrame implements ActionListener
{
	public String inputString = "";
	public String textfieldString = "";
	public String inputMask = "*";//mask
	public String temp = "";
	int i,j;
	
	JTextField tfInput = new JTextField(1);
	JLabel lblMessage = new JLabel("Guess A Letter: ");
	JLabel maskedWord = new JLabel();
	JLabel guessedLetter = new JLabel();
	JButton btnOK = new JButton("OK");
	JLabel timer = new JLabel("*-----");
	
	public TimeBomb() //constructor for GUI
	{
		super("Time Bomb Game");
	
		inputString = JOptionPane.showInputDialog("Enter Secret Word: ");//user enters secret word
		
		for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
		{
			temp +=  inputMask;//creates a mask of the secret word of the appropriate length
			maskedWord = new JLabel(temp);
		}
		

		Font f1 = new Font("Dialog", Font.PLAIN, 24);//set main font
		Font f2 = new Font("Dialog", Font.PLAIN, 32);//set larger font
		lblMessage.setFont(f1);
		tfInput.setFont(f1);
		guessedLetter.setFont(f1);
		btnOK.setFont(f1);
		timer.setFont(f2);
		maskedWord.setFont(f1);
		
		getContentPane().setLayout(new BorderLayout(1,1));//simple gui layout

		JPanel northPanel = new JPanel();
		northPanel.add(lblMessage);
		northPanel.add(tfInput);
		northPanel.add(btnOK);
		btnOK.addActionListener(this);
		getContentPane().add(northPanel, "North");
	
		JPanel centerPanel = new JPanel();
		centerPanel.add(maskedWord);
		centerPanel.add(guessedLetter);
		getContentPane().add(centerPanel, "Center");
		
		JPanel southPanel = new JPanel();
		southPanel.add(timer);//count down to explosion
		getContentPane().add(southPanel, "South");
		
		setSize(350, 200);//should be large enough on all platforms
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
	}
	

	
	public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))//OK button gets entered letter and puts it in the south panel
		{
			textfieldString = tfInput.getText();//string created from JTextField
			int len2 = textfieldString.length();//gets the length of the letter
			char[] letterArray = new char[len2];//creates array using len2
			for(int j = 0; j < len2; j++)
			{
				letterArray[j] = textfieldString.charAt(j);//populates array using textfieldString
			}
			
			int len = inputString.length();//gets the length of the secret word and stores it in len
			char[] secretWordArray = new char[len];//create array using len
			for(int i = 0; i < len; i++)
			{
				secretWordArray[i] = inputString.charAt(i);//populate array using inputString
			}
			
			for(int i = 0; i < inputString.length(); i++)
			{
				if(secretWordArray[i] == letterArray[j])
				{
					temp += textfieldString;
				}	
				else
				{
					temp += inputMask;
				}
			}
		}

	}//end of actionPerformed
	
	public static void main(String[] args) 
	{
		new TimeBomb();
	}
}//end TimeBomb class
```


----------



## FordGT90Concept (Oct 22, 2009)

You need to do something with "temp" once it exits the for loop (probably assign to both your equivilent of _Reveal and also to the text display).


----------



## Easy Rhino (Oct 22, 2009)

FordGT90Concept said:


> You need to do something with "temp" once it exits the for loop (probably assign to both your equivilent of _Reveal and also to the text display).



the problem tho is you cant do a .setText or a .getText with strings, only jlabels, jtextfields, etc.

edit! ok so the command is maskedWord.setText(temp);

however it is a little glitchy lol! it creates a whole new masked array with only the letter guessed revealed. so my code isnt perfect yet obviously. 
if i guess a letter wrong it creates a whole new ****** and if i guess a letter right it creates s***** and then when i guess another letter right it creates a new se**** so it jus t keeps making them and my field has ******s******e****** just running on. 

so i need to have it override the original maskedWord and keep the letters correctly guessed.


----------



## FordGT90Concept (Oct 22, 2009)

You have to update your equvilent of _Reveal so every time the code is executed, it is comparing the _Secret to the current _Reveal.

If you are dealing with strings:
Get: (something) = myvar;
Set: myvar = (something);

set variable = get variable


----------



## Easy Rhino (Oct 22, 2009)

uhm, ok let me work on this a bit.


----------



## Easy Rhino (Oct 22, 2009)

well i cant seem to troubleshoot this issue. here is my actionPerformed()

you can see the arrays are populated here and then compared using a for statement. temp is actually equal to the masked string which happens in the constructor. so then i want textFieldString, which is the letter entered in the JTextField, to += temp. but it only puts out the guessed letter and keeps the initial temp mask.


```
public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))//OK button gets entered letter and puts it in the south panel
		{
			textfieldString = tfInput.getText();//string created from JTextField
			int len2 = textfieldString.length();//gets the length of the letter
			char[] letterArray = new char[len2];//creates array using len2
			for(int j = 0; j < len2; j++)
			{
				letterArray[j] = textfieldString.charAt(j);//populates array using textfieldString
			}
			
			int len = inputString.length();//gets the length of the secret word and stores it in len
			char[] secretWordArray = new char[len];//create array using len
			for(int i = 0; i < len; i++)
			{
				secretWordArray[i] = inputString.charAt(i);//populate array using inputString
			}
			
			
			for(int i = 0; i < inputString.length(); i++)
			{
				if(secretWordArray[i] == letterArray[j])
				{
					temp += textfieldString;
					
				}
				else
				{
					temp += inputMask;
					timer.setText(boom.getText());
				}
				
			}
			maskedWord.setText(temp);
			
		}

	}//end of actionPerformed
```


----------



## FordGT90Concept (Oct 22, 2009)

You could use String.getChar() instead of copying it manually.

e.g.

```
textfieldString.getChars(0, textfieldString.length() - 1, letterArray, 0);
```


Once you have your temp populated, you'll want to do "new JTextField(temp)" to update that JTextField or, if possible, .setText("temp").  "temp" should be defined as a String.


----------



## Easy Rhino (Oct 22, 2009)

i did a little trouble shooting by adding 

System.out.println(temp) to my if statement. like so...


```
for(int i = 0; i < inputString.length(); i++)
			{
				if(secretWordArray[i] == letterArray[j])
				{
					System.out.println(temp);
					temp += textfieldString;
					System.out.println(temp);
				}
				else
				{
					temp += inputMask;
					System.out.println(temp);
				}
			}
			maskedWord.setText(temp);
```

if the secret word is secret then the console prints out that temp is equal too...

******    <--- this is temp before textfieldString is += to it
******s  <--- this is temp after textfieldString is += to it
******s*  <--- and the next 5 lines are what happens in the else statement temp += inputMask 
******s**
******s***
******s****
******s*****

im not sure why it runs both the if and else part of the code. isnt it either or??? (if the letter does match a letter in the secret word it runs both, if it doesnt match it only runs else) and this explains that with temp += textfieldString it is only adding the entered letter onto the mask, NOT replacing the * with the letter. 

so ive screwed something up somewhere.


----------



## FordGT90Concept (Oct 22, 2009)

temp needs to be cleared (temp = "") before it is used (the for loop).


----------



## Easy Rhino (Oct 22, 2009)

FordGT90Concept said:


> temp needs to be cleared (temp = "") before it is used (the for loop).



hrm, i think i am getting there. except if my if else statement when the letter is correct is does both if and else!! and when it is incorrect is only does else(like it should here)


----------



## FordGT90Concept (Oct 22, 2009)

It can never do if and else with the same evaluation.  It has to be reevaluated to send it on a different code path.


----------



## Easy Rhino (Oct 22, 2009)

FordGT90Concept said:


> It can never do if and else with the same evaluation.  It has to be reevaluated to send it on a different code path.



i dont want it to do if and else, but it is. that is the strange thing.


----------



## FordGT90Concept (Oct 22, 2009)

It is an impossibility for it to do both.  The syntax is correct.


----------



## Easy Rhino (Oct 22, 2009)

FordGT90Concept said:


> It is an impossibility for it to do both.  The syntax is correct.



weird glitch. anyway, i cant seem to replace the correct letter with the correct *. += just addes the letter to the existing mask, it doesnt replace the correct * with the letter.


----------



## FordGT90Concept (Oct 22, 2009)

In a String, you can't replace just one letter.  That's why you append it.  You are creating a new string one charater at a time.

Edit: Did you put that temp = ""; in there yet?

```
temp = "";
			for(int i = 0; i < inputString.length(); i++)
			{
				if(secretWordArray[i] == letterArray[j])
				{
					temp += textfieldString;
					
				}
				else
				{
					temp += inputMask;
					timer.setText(boom.getText());
				}
				
			}
			maskedWord.setText(temp);
```


----------



## Easy Rhino (Oct 22, 2009)

FordGT90Concept said:


> In a String, you can't replace just one letter.  That's why you append it.  You are creating a new string one charater at a time.
> 
> Edit: Did you put that temp = ""; in there yet?
> 
> ...



yes i put temp = ""; in there and it simply wipes out the value of temp but that doesnt really solve my issue. my issue is that when i choose a letter if it is correct it replaces the *.

i want this to happen. secret word is secret
it creates a mask ******
i guess s
the output on the gui is now s*****
i guess e
the output on the gui is now se**e*
i guess t
the output on the gui is now se**et
and so on. 

so with my current code it totally replaces ****** with s
and then when i enter e it reads ee
and when i enter t it reads t

so it isnt 
1) replacing * with the correct letter
2) storing that value in memory

NOTE: my algorithm is going to blow my professor away lol.


----------



## FordGT90Concept (Oct 22, 2009)

```
secretWordArray[i] == letterArray[j]
```

You have i and j there.  they should both be i or j (most likely i).


----------



## Easy Rhino (Oct 22, 2009)

FordGT90Concept said:


> ```
> secretWordArray[i] == letterArray[j]
> ```
> 
> You have i and j there.  they should both be i or j (most likely i).



they have to be different or the program poops out a massive error listing

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1
	at TimeBomb.actionPerformed(TimeBomb.java:107)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2012)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2335)
	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:404)
	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:253)
	at java.awt.Component.processMouseEvent(Component.java:6108)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3276)
	at java.awt.Component.processEvent(Component.java:5873)
	at java.awt.Container.processEvent(Container.java:2105)
	at java.awt.Component.dispatchEventImpl(Component.java:4469)
	at java.awt.Container.dispatchEventImpl(Container.java:2163)
	at java.awt.Component.dispatchEvent(Component.java:4295)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4461)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4125)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4055)
	at java.awt.Container.dispatchEventImpl(Container.java:2149)
	at java.awt.Window.dispatchEventImpl(Window.java:2478)
	at java.awt.Component.dispatchEvent(Component.java:4295)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:604)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)


----------



## FordGT90Concept (Oct 22, 2009)

Why are they not equal in length?


----------



## Easy Rhino (Oct 22, 2009)

FordGT90Concept said:


> Why are they not equal in length?



letterArray is obviously only going to be 1 char long and secretWordArray is going to be however long inputString is.


----------



## FordGT90Concept (Oct 23, 2009)

If that is the case, then you aren't comparing your equivlent of _Secret and _Reveal.  You must perform that comparison in order to update your display (temp).  Without it, you would get "s*****" on the first one then "*e**e*" on the second instead of "se**e*"


If the array is only one character long, it should be a char instead of an array.  String.charAt(0) to get the first character of a String.


----------



## Easy Rhino (Oct 23, 2009)

FordGT90Concept said:


> If that is the case, then you aren't comparing your equivlent of _Secret and _Reveal.  You must perform that comparison in order to update your display (temp).  Without it, you would get "s*****" on the first one then "*e**e*" on the second instead of "se**e*"
> 
> 
> If the array is only one character long, it should be a char instead of an array.  String.charAt(0) to get the first character of a String.



so let me double check then...this line


```
if(secretWordArray[i] == textfieldString.charAt(0))
```

says that if the char at position 0 on textfieldString is equal to any of the characters in the array secretWordArray...

right?


----------



## Easy Rhino (Oct 23, 2009)

my prof just told me that it would be easier to use the indexof() and lastindexof() methods to determine if the letter is part of the word. so i should go with strings rather than arrays. bah,

now i am totally lost.


----------



## FordGT90Concept (Oct 23, 2009)

Easy Rhino said:


> so let me double check then...this line
> 
> 
> ```
> ...


The if statement only checks one.  The for loop makes it run the if statement for the length of secretWordArray.

I converted Magic to Java for you:

```
private Boolean Magic(char letter)
	{
		Boolean hit = false;

		String temp = "";
		for (int i = 0; i < secretWordArray.length(); i++)
		{
			if (textfieldString.charAt(i) == inputMask.charAt(i))
			{
				if (letter == secretWordArray.charAt(i))
				{
					temp += secretWordArray.charAt(i);
					hit = true;
				}
				else
				{
					temp += inputMask.charAt(i);
				}
			}
			else
			{
				temp += textfieldString.charAt(i);
			}
		}
		textfieldString = temp;

		return hit;
	}
```
I didn't test it but what it is trying to do is exactly what you need.  Notice how there is more than one if statement.

After running that code, you would still have to update the GUI with the text.


What IDE are you using to create this?


----------



## Easy Rhino (Oct 23, 2009)

ok, in Magic(char letter) 

secretWordArray is actually inputString.length() since you cant do a .length on an array. but that is fine since i guess Strings will be easier to work with. 

the actionPerformed method is a toughy. when the user clicks the OK button it takes the text from tfInput and puts it in the string textfieldString. then i want to execute Magic. however it doesnt like the arguments for magic. 


```
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class timebombtest extends JFrame implements ActionListener
{
	public String inputString = "";
	public String textfieldString = "";
	public String inputMask = "*";//mask
	public String mask = "";
	public String temp = "";
	
	JTextField tfInput = new JTextField(2);
	JLabel lblMessage = new JLabel("Guess A Letter: ");
	JLabel maskedWord = new JLabel();
	JLabel guessedLetter = new JLabel();
	JButton btnOK = new JButton("OK");
	JLabel timer = new JLabel("*-----");
	
	
	public timebombtest() //constructor for GUI
	{
		super("Time Bomb Game");
		
		inputString = JOptionPane.showInputDialog("Enter Secret Word: ");//user enters secret word
		
		for(int i = 0; i < inputString.length(); i++)//gets the length of the secret word
			temp +=  inputMask;//creates a mask of the secret word of the appropriate length
			maskedWord = new JLabel(temp);		

		
		//set font
		Font f1 = new Font("Dialog", Font.PLAIN, 24);//set main font
		Font f2 = new Font("Dialog", Font.PLAIN, 32);//set larger font
		lblMessage.setFont(f1);
		tfInput.setFont(f1);
		guessedLetter.setFont(f1);
		btnOK.setFont(f1);
		timer.setFont(f2);
		maskedWord.setFont(f1);
		
		//gui properties
		getContentPane().setLayout(new BorderLayout(1,1));

		JPanel northPanel = new JPanel();
		northPanel.add(lblMessage);
		northPanel.add(tfInput);
		northPanel.add(btnOK);
		btnOK.addActionListener(this);
		getContentPane().add(northPanel, "North");
	
		JPanel centerPanel = new JPanel();
		centerPanel.add(maskedWord);
		centerPanel.add(guessedLetter);
		getContentPane().add(centerPanel, "Center");
		
		JPanel southPanel = new JPanel();
		southPanel.add(timer);
		getContentPane().add(southPanel, "South");
		
		setSize(350, 200);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	private Boolean Magic(char letter)
	{
		Boolean hit = false;

		String temp = "";
		for (int i = 0; i < inputString.length(); i++)
		{
			if (textfieldString.charAt(i) == inputMask.charAt(i))
			{
				if (letter == inputString.charAt(i))
				{
					temp += inputString.charAt(i);
					hit = true;
				}
				else
				{
					temp += inputMask.charAt(i);
				}
			}
			else
			{
				temp += textfieldString.charAt(i);
			}
		}
		textfieldString = temp;

		return hit;
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))
		{
			textfieldString = tfInput.getText();
			Magic();
		}
	}
	
	public static void main(String[] args) 
	{
		new timebombtest();
	}
}//end TimeBomb class
```

im using Eclipse !


----------



## FordGT90Concept (Oct 23, 2009)

The argument should be the letter the user input.  My guess is you should do Magic(tfInput.getText().charAt(0)).  After you call Magic, make sure to update your bomb if Magic returns false.

Rename the "temp" outside of Magic to "reveal" or something else.  "temp" should only exist inside of Magic.


```
public String mask = "";
```
mask should be a char and it should be set once with initilization and used after that point instead of using .charAt() to access it.

It is Array.length instead of Array.length().


Eclipse should allow you to use break points to see what is in variables at that point in the application.  It is very helpful.


----------



## Easy Rhino (Oct 23, 2009)

this doesnt work. cant invoke charAt(int) on the array type char[]


```
if (letter == secretWordArray.charAt(i))
				{
					temp += secretWordArray.charAt(i);
					hit = true;
```


----------



## FordGT90Concept (Oct 23, 2009)

If it is defined as a char[] array, use brackets:

secreWordArray_


.charAt() only applies to Strings._


----------



## Easy Rhino (Oct 23, 2009)

i think it all comes down to actionPerformed...

also, in Magic... inputMask is a class level variable String

public String inputMask = "*";

while mask is

public char mask = '*';

so how would you suggest i encounter that?


```
public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))
		{
			textfieldString = tfInput.getText();
			Magic(tfInput.getText().charAt(0));
		}
	}
```

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at timebombtest.Magic(timebombtest.java:91)
	at timebombtest.actionPerformed(timebombtest.java:120)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2012)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2335)
	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:404)
	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:253)
	at java.awt.Component.processMouseEvent(Component.java:6108)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3276)
	at java.awt.Component.processEvent(Component.java:5873)
	at java.awt.Container.processEvent(Container.java:2105)
	at java.awt.Component.dispatchEventImpl(Component.java:4469)
	at java.awt.Container.dispatchEventImpl(Container.java:2163)
	at java.awt.Component.dispatchEvent(Component.java:4295)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4461)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4125)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4055)
	at java.awt.Container.dispatchEventImpl(Container.java:2149)
	at java.awt.Window.dispatchEventImpl(Window.java:2478)
	at java.awt.Component.dispatchEvent(Component.java:4295)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:604)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)


----------



## FordGT90Concept (Oct 23, 2009)

Easy Rhino said:


> i think it all comes down to actionPerformed...
> 
> also, in Magic... inputMask is a class level variable String


I guessed what names belonged where because I don't follow your naming at all.   I think you had a variable missing (equivilent of reveal) but I really don't know.




Easy Rhino said:


> public String inputMask = "*";
> 
> while mask is
> 
> ...


I don't follow?  You can make a char a string by appending it to an empty string.  e.g.

```
inputMask += mask;
```
The two should now equal although doing so is kind of pointless.



There's a NullPointerException at Magic(timebombtest.java:91).  If you can copy that area and point out which line is 91, I should be able to help you with that.


----------



## Easy Rhino (Oct 23, 2009)

FordGT90Concept said:


> I guessed what names belonged where because I don't follow your naming at all.   I think you had a variable missing (equivilent of reveal) but I really don't know.
> 
> 
> 
> ...




```
for (int i = 0; i < secretWordArray.length; i++)
```

and here is my entire code


```
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class timebombtest extends JFrame implements ActionListener
{
	public String inputString = "";
	public String textfieldString = "";
	public String inputMask = "*";
	public char mask = '*';
	public String hidereveal = "";
	public char[] secretWordArray;
	
	JTextField tfInput = new JTextField(2);
	JLabel lblMessage = new JLabel("Guess A Letter: ");
	JLabel maskedWord = new JLabel();
	JLabel guessedLetter = new JLabel();
	JButton btnOK = new JButton("OK");
	JLabel timer = new JLabel("*-----");
	
	
	public timebombtest() //constructor for GUI
	{
		super("Time Bomb Game");
		
		inputString = JOptionPane.showInputDialog("Enter Secret Word: ");//user enters secret word
		textfieldString = tfInput.getText();
		
		for(int i = 0; i < inputString.length(); i++)
		{
			hidereveal +=  mask;//creates a mask of the secret word of the appropriate length
			maskedWord = new JLabel(hidereveal);		
		}
		
		int len = inputString.length();//gets the length of the secret word and stores it in len
		char[] secretWordArray = new char[len];//create array using len
		for(int i = 0; i <inputString.length(); i++)
		{
			secretWordArray[i] = inputString.charAt(i);//populate array using inputString
		}

		//set font
		Font f1 = new Font("Dialog", Font.PLAIN, 24);//set main font
		Font f2 = new Font("Dialog", Font.PLAIN, 32);//set larger font
		lblMessage.setFont(f1);
		tfInput.setFont(f1);
		guessedLetter.setFont(f1);
		btnOK.setFont(f1);
		timer.setFont(f2);
		maskedWord.setFont(f1);
		
		//gui properties
		getContentPane().setLayout(new BorderLayout(1,1));

		JPanel northPanel = new JPanel();
		northPanel.add(lblMessage);
		northPanel.add(tfInput);
		northPanel.add(btnOK);
		btnOK.addActionListener(this);
		getContentPane().add(northPanel, "North");
	
		JPanel centerPanel = new JPanel();
		centerPanel.add(maskedWord);
		centerPanel.add(guessedLetter);
		getContentPane().add(centerPanel, "Center");
		
		JPanel southPanel = new JPanel();
		southPanel.add(timer);
		getContentPane().add(southPanel, "South");
		
		setSize(350, 200);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	private Boolean Magic(char letter)
	{
		Boolean hit = false;

		String temp = "";
		for (int i = 0; i < secretWordArray.length; i++)
		{
			if (textfieldString.charAt(i) == inputMask.charAt(i))
			{
				if (letter == secretWordArray[i])
				{
					temp += secretWordArray[i];
					hit = true;
				}
				else
				{
					temp += inputMask.charAt(i);
				}
			}
			else
			{
				temp += textfieldString.charAt(i);
			}
		}
		textfieldString = temp;

		return hit;
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))
		{
			Magic(tfInput.getText().charAt(0));
		}
	}
	
	public static void main(String[] args) 
	{
		new timebombtest();
	}
}//end TimeBomb class
```


----------



## FordGT90Concept (Oct 23, 2009)

secretWordArray is null in Magic.

Edit:

```
private Boolean Magic(char letter)
	{
		Boolean hit = false;

		String temp = "";
		for (int i = 0; i < inputString.length(); i++)
		{
			if (hidereveal.charAt(i) == mask)
			{
				if (hidereveal.charAt(i) == inputString.charAt(i))
				{
					temp += inputString.charAt(i);
					hit = true;
				}
				else
				{
					temp += mask;
				}
			}
			else
			{
				temp += hidereveal.charAt(i);
			}
		}
		hidereveal = temp;

		return hit;
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))
		{
			if (tfInput.getText().length() > 0)
			{
			Magic(tfInput.getText().charAt(0));
			tfInput.setText(""); // clear for next letter
			maskedWord.setText(hidereveal);
			}
		}
	}
```

Before running Magic, make sure inputString has a value (e.g. "blamo"), make sure hidereveal matches inputString in length but containing all masks (e.g. "*****").


----------



## Easy Rhino (Oct 23, 2009)

k i did a little troubleshooting with System.out.println and i noticed that in Magic that while 
hidereveal does equal the number letters in the secret word it does not equal mask. 

the mask before the for statement equals *

but after the for statement ( the secret word is awesome(7 letters) it shows

*
*
*
*
*
*
*

so 1 for every letter


----------



## FordGT90Concept (Oct 23, 2009)

mask should always be *

Only hidereveal and temp should change.  temp is especially the one to watch because it is merging hidereveal, the letter, and inputString.


I don't see a problem.


----------



## Easy Rhino (Oct 23, 2009)

for this code


```
private Boolean Magic(char letter)
	{
		Boolean hit = false;

		String temp = "";
		System.out.println("inputString = " + inputString);
		System.out.println("hidereveal = " + hidereveal);
		System.out.println("mask = " + mask);
		for (int i = 0; i < inputString.length(); i++)
		{
			if (hidereveal.charAt(i) == mask)
			{
				System.out.println("mask = " + mask);
				if (hidereveal.charAt(i) == inputString.charAt(i))
				{
					temp += inputString.charAt(i);
					System.out.println("temp = " + temp);
					hit = true;
				}
				else
				{
					temp += mask;
					System.out.println("temp = " + temp);
					System.out.println("mask = " + mask);
				}
			}
			else
			{
				temp += hidereveal.charAt(i);
			}
		}
		hidereveal = temp;
```

i get this in console

inputString = awesome
hidereveal = *******
mask = *
mask = *
temp = *
mask = *
mask = *
temp = **
mask = *
mask = *
temp = ***
mask = *
mask = *
temp = ****
mask = *
mask = *
temp = *****
mask = *
mask = *
temp = ******
mask = *
mask = *
temp = *******
mask = *


as you can see inputString does equal the correct value and hidereveal equals the exact amount of necessary * but inputString.charAt(i) never adds anything to temp. and then it just keeps looping asterisks.


----------



## FordGT90Concept (Oct 23, 2009)

What's the letter you gave to Magic?


----------



## Easy Rhino (Oct 23, 2009)

FordGT90Concept said:


> What's the letter you gave to Magic?



a


----------



## FordGT90Concept (Oct 23, 2009)

I think I see the bug.  I check my code...


```
System.out.println("mask = " + mask);
				if (hidereveal.charAt(i) == inputString.charAt(i))
				{
					temp += inputString.charAt(i);
					System.out.println("temp = " + temp);
					hit = true;
				}
				else
				{
					temp += mask;
					System.out.println("temp = " + temp);
					System.out.println("mask = " + mask);
				}
```
change to:

```
System.out.println("mask = " + mask);
				if (letter == inputString.charAt(i))
				{
					temp += inputString.charAt(i);
					System.out.println("temp = " + temp);
					hit = true;
				}
				else
				{
					temp += mask;
					System.out.println("temp = " + temp);
					System.out.println("mask = " + mask);
				}
```

I deleted the "letter" bit.   temp should then be correct.


----------



## Easy Rhino (Oct 23, 2009)

damn man, id celebrate but im too exhausted  

ok, so now i just have to work on the timer. im guessing i should put some sort of for loop inside the nested else statement...


----------



## FordGT90Concept (Oct 23, 2009)

When Magic (recommend you change the name of that to something more descriptive, by the way) return false, redraw the timer.  I'd use a for loop to create the dashes.


----------



## Easy Rhino (Oct 23, 2009)

FordGT90Concept said:


> When Magic (recommend you change the name of that to something more descriptive, by the way) return false, redraw the timer.  I'd use a for loop to create the dashes.



shouldnt i put a hit = false; after

temp += hidereveal.charAt(i);

sidenote: what exactly is letter doing in your magic method?


----------



## FordGT90Concept (Oct 23, 2009)

It depends on how creative you want to get with it.


----------



## Easy Rhino (Oct 23, 2009)

not sure what is going on here but if you guess wrong on the very first guess it does not deduct 1. you have to guess right first and then no matter what your guess the second time it deducts 1. 

am i putting the timer in the wrong spot??
hit = false; isnt necessary is it since we declare it false before the for loop runs?


----------



## FordGT90Concept (Oct 23, 2009)

if (!Magic(char))
{
  // decrement timer
}

Don't do anything if it returns true.


----------



## Easy Rhino (Oct 24, 2009)

FordGT90Concept said:


> if (!Magic(char))
> {
> // decrement timer
> }
> ...



yea but what section do i put that in?


----------



## FordGT90Concept (Oct 24, 2009)

The button click action performed.


----------



## Easy Rhino (Oct 24, 2009)

right now i set it up to simply count down to 0 and go boom when ever the user enters a letter right or wrong. here is my code for that. now i need ot get actionPerformed to recognize the boolean hit results from compareSecret.

int guessedWrong = 5;   // class level variable
JLabel timer = new JLabel(" ==- 5 -== ");   //  class level variable that represents the initial value of gussedWrong


```
public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))
		{
			if (tfInput.getText().length() > 0)
			{
			compareSecret(tfInput.getText().charAt(0));
			tfInput.setText(""); // clear for next letter
			maskedWord.setText(hidereveal);

			guessedWrong--; // subtract 1 from guessedWrong
			String wrongGuess = String.valueOf(guessedWrong); // turn the int gussedWrong into a String so it can be put into setText
			timer.setText(" ==- " + wrongGuess + " -== "); // place the value of guessedWrong into the JLabel timer. 
			if(guessedWrong == 0) // set condition for BOOM!
			{
				timer.setText("BOOM!"); // set "BOOM!"
			}
			}
			
		}

	}
```


----------



## FordGT90Concept (Oct 24, 2009)

I think (note the Boolean hit = )...

```
public void actionPerformed(ActionEvent e)
	{
		if ("OK".equals(e.getActionCommand()))
		{
			if (tfInput.getText().length() > 0)
			{
				Boolean hit = compareSecret(tfInput.getText().charAt(0));
				tfInput.setText(""); // clear for next letter
				maskedWord.setText(hidereveal);
				
				if (!hit)
				{
					guessedWrong--; // subtract 1 from guessedWrong
					String wrongGuess = String.valueOf(guessedWrong); // turn the int gussedWrong into a String so it can be put into setText
					timer.setText(" ==- " + wrongGuess + " -== "); // place the value of guessedWrong into the JLabel timer. 
					if(guessedWrong == 0) // set condition for BOOM!
					{
						timer.setText("BOOM!"); // set "BOOM!"
					}
				}
			}
			
		}

	}
```


----------



## Easy Rhino (Oct 24, 2009)

yup that did it.


----------



## Easy Rhino (Oct 29, 2009)

miss me?? 

ok im taking an old program and converting it to an applet. the original program was the elementary math program where using JOptionPane the user receives a basic addition or subtraction question and then enters their answer and the program tells them if they are correct or incorrect. 

so now im converting it to an applet that does the same thing but on a GUI. here is what i have so far. i need to figure out a way to retrieve the textfield input and see if it matches the actual answer.
(note: i dont think i should use a switch statement here but im still in the process of reworking code)


```
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class TeachArithmetic extends JApplet implements ActionListener
{
	private JPanel mathProblem = new JPanel();
	private JPanel enterAnswer = new JPanel();
	private JPanel gradeAnswer = new JPanel();
	private JPanel clickButton = new JPanel();
	private JPanel mainPanel = new JPanel();
	
	private JLabel problem;
	private JTextField userInput = new JTextField(5);
	private JLabel printResult;
	private JButton ok, next;
	
	public void init()
	{
		
		ok = new JButton("OK");
		ok.addActionListener(this);
		ok.setFont(new Font("Comic Sans MS", Font.BOLD,18));
		ok.setForeground(Color.blue);
		ok.setBackground(Color.white);
		
		next = new JButton("NEXT");
		next.addActionListener(this);
		next.setFont(new Font("Comic Sans MS", Font.BOLD,18));
		next.setForeground(Color.blue);
		next.setBackground(Color.white);
		
		mathProblem.setBackground(Color.white);
		mathProblem.setForeground(Color.green);
		mathProblem.add(problem);
		
		enterAnswer.setBackground(Color.white);
		enterAnswer.add(userInput);
		
		gradeAnswer.setBackground(Color.white);
		gradeAnswer.setFont(new Font("Comic Sans MS", Font.BOLD,20));
		gradeAnswer.setForeground(Color.red);
		gradeAnswer.add(printResult);
		
		clickButton.setBackground(Color.white);
		clickButton.add(ok);
		clickButton.add(next);	
		
		mainPanel.setBackground(Color.white);			
		mainPanel.setLayout(new GridLayout(5, 1));
		mainPanel.add(mathProblem);
		mainPanel.add(enterAnswer);
		mainPanel.add(gradeAnswer);
		mainPanel.add(clickButton);
		
		
		Container pane = getContentPane();
		pane.add(mainPanel);
		
	}
	
		public void actionPerformed(ActionEvent e)
		{
			
			if(e.getSource() == ok)
			{
				//check answer to see if it is correct
				//if correct then print correct
				//if incorrect then print incorrect
			}
			if(e.getSource() == next)
			{
				generateProblem(); //generate new math problem
				printResult.setText(""); //clear screen
				userInput.setText(""); //clear textfield
			}
		}
		
		public void generateProblem()
		{
			int num1 = randomNumber();
			int num2 = randomNumber();

			int user_answer = 0;
			int correct_answer = 0;
			boolean correct = false;
			
			switch(simple_math)
			{
				case 1: //addition
					user_answer = num1 + num2; 
					correct_answer = num1 + num2;
					if (user_answer == correct_answer)
					{
						correct = true;
					}
					else
					{
						correct = false;
					}
					break;
				case 2: //subtraction
					if (num1 < num2)// larger number is first
					{
						int num3 = num1;
						num2 = num1;
						num1 = num3;
					}
					user_answer = num1 - num2;
					correct_answer = num1 - num2;
					if (user_answer == correct_answer)
					{
						correct = true;
					}
					else
					{
						correct = false;
					}
					break;
			}
			if(correct)
			{
				printResult.setText("You got it right!");
			}
			else
			{
				printResult.setText("I'm sorry, but that is incorrect.");
			}
		}
		
		public int randomNumber()
		{
			return ((int) (Math.random() * 10));
		}
	
}
```


----------



## Easy Rhino (Oct 31, 2009)

edit: solved! just had to run Integer.parseInt on userInput.getText() and it works like a charm.

ok, applet is almost done. i just need to figure out a way to get the number which is input into the textfield to be equal to my class variable user_answer. the problem is i cant grab that entered number and put it into a int variable. 

this doesnt work


```
user_answer = userInput.getText(); //set what the user enters into the textfield as the user answer
```


```
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;

public class TeachArithmetic extends JApplet implements ActionListener
{
	public int num1, num2, num3, num4;
	public int user_answer, correct_answer;
	
	private JPanel mathProblem = new JPanel();
	private JPanel enterAnswer = new JPanel();
	private JPanel gradeAnswer = new JPanel();
	private JPanel clickButton = new JPanel();
	private JPanel mainPanel = new JPanel();
	
	private JTextArea problem = new JTextArea(1, 3);
	private JTextField userInput = new JTextField(3);
	private JTextArea printResult = new JTextArea(1, 3);
	private JButton ok, next;
	private Border blueline1 = BorderFactory.createLineBorder(Color.blue);
	
	public void init()
	{
		
		ok = new JButton("OK");
		ok.addActionListener(this);
		ok.setFont(new Font("Comic Sans MS", Font.BOLD,25));
		ok.setForeground(Color.blue);
		ok.setBackground(Color.white);
		
		next = new JButton("NEXT");
		next.addActionListener(this);
		next.setFont(new Font("Comic Sans MS", Font.BOLD,25));
		next.setForeground(Color.blue);
		next.setBackground(Color.white);
		
		mathProblem.setBackground(Color.white);
		mathProblem.setForeground(Color.green);
		mathProblem.add(problem);
		
		enterAnswer.setBackground(Color.white);
		enterAnswer.add(userInput);
		userInput.setFont(new Font("Comic Sans MS", Font.BOLD,22));
		
		gradeAnswer.setBackground(Color.white);
		gradeAnswer.setFont(new Font("Comic Sans MS", Font.BOLD,22));
		gradeAnswer.setForeground(Color.red);
		gradeAnswer.add(printResult);
		
		clickButton.setBackground(Color.white);
		clickButton.add(ok);
		clickButton.add(next);	
		
		mainPanel.setBackground(Color.white);			
		mainPanel.setLayout(new GridLayout(5, 1));
		mainPanel.add(mathProblem);
		mainPanel.add(enterAnswer);
		mainPanel.add(gradeAnswer);
		mainPanel.add(clickButton);
		mainPanel.setBorder(blueline1);
		
		
		Container pane = getContentPane();
		pane.add(mainPanel);
		
		
	}
	
		public void actionPerformed(ActionEvent e)
		{
			
			if(e.getSource() == ok)
			{
				if(user_answer == correct_answer)
				{
					printResult.setText("You Got It Right!");
					printResult.setFont(new Font("Comic Sans MS", Font.BOLD,18));
					printResult.setForeground(Color.green);
				}
				else
				{
					printResult.setText("I'm Sorry But That Is Incorrect.");
					printResult.setFont(new Font("Comic Sans MS", Font.BOLD,18));
					printResult.setForeground(Color.red);
				}
			}
			if(e.getSource() == next)
			{
				randomNumber(); //generate random int
				displayProblem(); //generate new math problem
				printResult.setText(""); //clear screen
				userInput.setText(""); //clear textfield
			}
		}
		
		
		public void randomNumber()
		{
			num1 = (int) (Math.random() * 10);
			num2 = (int) (Math.random() * 10);
			num3 = (int) (Math.random() * 10);
			num4 = (int) (Math.random() * 10);
		}
		
		public void displayProblem()
		{
			problem.setText("Your Math Problem is: " + num1 + " + " + num2);
		    problem.setFont(new Font("Comic Sans MS", Font.BOLD,20));
		    problem.setForeground(Color.black);
		    user_answer = userInput.getText(); //set what the user enters into the textfield as the user answer
		    correct_answer = num1 + num2; //set the correct answer to whatever num1 + num2 equals. 
		}
	
}//end of class
```

edit: solved! just had to run Integer.parseInt on userInput.getText() and it works like a charm.


----------



## Easy Rhino (Nov 18, 2009)

i'm working on a simple IO program that takes a text file and reads from it and then writes a new text file with some parameters i create using methods. the program works and creates the file but the text file is empty. it isnt actually writing anything to it. i cant for the life of me figure out why! here is my code


```
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;


public class projectIO 
{	
	StringTokenizer tokenizer;
	BufferedReader inFile;
	PrintWriter outFile;	
	
	private String title, inputString;
	private int quantity;
	private double price;
	
	projectIO()
	{
		try
		{
			inFile = new BufferedReader(new FileReader("books.txt"));
			outFile = new PrintWriter(new FileWriter("report.txt"));
			write_report_heading();
			read_data();
			inFile.close();
			outFile.close();
			
		}
		catch(Exception e)
		{
			if(e instanceof FileNotFoundException)
			{
				System.out.println("FILENAME NOT FOUND");
				System.exit(1);
			}			
		}		
	}// end of projectIO constructor
	
	public void read_data() throws IOException
	{
		inputString = inFile.readLine();
		
		while(inputString != null)
		{
			tokenizer = new StringTokenizer(inputString, ",");
			title = tokenizer.nextToken();
			quantity = Integer.parseInt(tokenizer.nextToken());
			price = Double.parseDouble(tokenizer.nextToken());
			
			write_record();
			
			inputString = inFile.readLine();
		}// end of while loop
	}// end of read_data
	
	public void write_record() throws IOException
	{
		outFile.print(quantity);
		outFile.print(price);
		outFile.println(title);
	}
	
	public void write_report_heading() throws IOException
	{
		outFile.print("STOCK REPORT ON BOOKS");
		outFile.println();
		outFile.print("Quantity \t\t Price \t\t Title\n");
		outFile.println();
		
	}
	
	public static void main(String[] args)
	{
		new projectIO();
	}
}// end of class
```


----------



## FordGT90Concept (Nov 18, 2009)

Make sure to frequently flush the data.  Flush basically means to commit the changes (aka, write the data to the hard drive).  No flush means the file is merely "theoretical."

http://java.sun.com/j2se/1.4.2/docs/api/java/io/PrintWriter.html

You should try to flush approximately every 4096 bytes.


----------



## Easy Rhino (Nov 18, 2009)

ah i see, but we the program isnt that detailed for those needs. i was given an example file and it worked fine but my program seems to be missing something.


----------



## FordGT90Concept (Nov 18, 2009)

Did you add flushes?  It doesn't look like much data so just do outFile.flush() before outfile.close().


Also, make sure it isn't throwing an exception.


----------



## Easy Rhino (Nov 18, 2009)

FordGT90Concept said:


> Did you add flushes?  It doesn't look like much data so just do outFile.flush() before outfile.close().
> 
> 
> Also, make sure it isn't throwing an exception.



yea the flush didnt work. im going to email my prof about this. perhaps it is an issue with the text file he supplied us because this is supposed to be a fairly straight forward exercise.


----------



## Easy Rhino (Nov 19, 2009)

ok apparently im dumb because it wasnt working for the most obvious reason. i had the variables out of order between read_data and write_record. anyway it is outputting the data and i got the formatting worked out. 

now the last part of the problem is to get it to total the amount of books in stock and total the value of the books in stock . i can easily get the quantity and the value of one book but i cant seem to get the program to hold the quantity over while the loop continues and then add the second book quantity onto the first. 


```
import java.io.*;
import java.util.*;


public class projectIO 
{	
	StringTokenizer tokenizer;
	BufferedReader inFile;
	PrintWriter outFile;	
	
	private String title, inputString;
	private int quantity, bookStock;
	private double price, value;
	
	projectIO()
	{
		try
		{
			inFile = new BufferedReader(new FileReader("books.txt"));
			outFile = new PrintWriter(new FileWriter("report.txt"));
			write_report_header();
			read_data();
			write_report_footer();
			inFile.close();
			outFile.close();
			
		}
		catch(Exception e)
		{
			if(e instanceof FileNotFoundException)
			{
				System.out.println("FILENAME NOT FOUND");
				System.exit(1);
			}			
		}		
	}// end of projectIO constructor
	
	public void read_data() throws IOException
	{
		inputString = inFile.readLine();
		
		while(inputString != null)
		{
			tokenizer = new StringTokenizer(inputString, ",");
			quantity = Integer.parseInt(tokenizer.nextToken());
			price = Double.parseDouble(tokenizer.nextToken());
			title = tokenizer.nextToken();
			
			write_record();
			
			inputString = inFile.readLine();
		}// end of while loop
	}// end of read_data
	
	public void write_record() throws IOException
	{
		if(quantity <= 1)
		{
			outFile.print("*** REORDER ***   \t" + quantity + "\t");
		}
		else
		{
			outFile.print("\t\t\t\t\t" + quantity + "\t");
		}
		outFile.print("\t\t  $" + price + "\t");
		outFile.println("\t" + title);
	}
	
	public void write_report_header() throws IOException
	{
		outFile.print("\t\t\t\t\t\tSTOCK REPORT ON BOOKS");
		outFile.println();
		outFile.println();
		outFile.print("\t\t\t\t\tQuantity \t  Price \t Title\n");
		outFile.println();
	}
	
	public void write_report_footer() throws IOException
	{
		outFile.println();
		outFile.print("Number of books in stock " + bookStock);
		outFile.println();
		outFile.println();
		outFile.print("Retail value of books in stock $" + value);
	}
	
	public static void main(String[] args)
	{
		new projectIO();
	}
}// end of class
```


----------



## Easy Rhino (Nov 19, 2009)

ok i figured it out. actually quite easy just had to remember that in a loop i can use the += operator to get the value to add itself onto another variable. so in my case i just did 


```
bookStock += quantity;
```

and it adds the amount of each title up and stores it. 

now to figure out value which is a bit trickier since it has to multiply the number of books by the price.

edit: lol nevermind it was easy. man i am getting tired.


----------

