I am building a simple game of 21. Everything comes together okay, but when I click on the Button that I have assigned to my 'Stand' function, none of the if-statement blocks trigger event though I am meeting conditions of one or the other depending on what cards have already been dealt. I have tested all variations of the statements and I want to have some insight, or a second pair of eyes to see something I do not.
I have tested the function multiple times, and re-written it multiple times. I've tested the function with just that statement present, and it still does not trigger.
This is the function in question:
//when player hits stand button
public void Stand(TextField playerNum, TextField dealerNum, TilePane b, Button hit, Button stand, Button deal, TextField handsLostNum, TextField handsWonNum) {
//obtain current final scores when player stands
playerFinal = Integer.parseInt(playerNum.getText());
dealerFinal = Integer.parseInt(dealerNum.getText());
if (playerFinal > dealerFinal) {
hit.setVisible(false);
stand.setVisible(false);
deal.setVisible(true);
playerNum.setText("YOU WIN!");
dealerNum.setText("YOU WIN!");
handsWon += 1;
String temp = Integer.toString(handsWon);
handsWonNum.setText(temp);
}
if (dealerFinal > playerFinal) {
hit.setVisible(false);
stand.setVisible(false);
deal.setVisible(true);
playerNum.setText("YOU LOSE!");
dealerNum.setText("YOU LOSE!");
handsLost += 1;
String temp = Integer.toString(handsLost);
handsLostNum.setText(temp);
}
if (dealerFinal == playerFinal) {
playerNum.setText("DRAW! PLAY AGAIN!");
dealerNum.setText("DRAW! PLAY AGAIN!");
hit.setVisible(false);
stand.setVisible(false);
deal.setVisible(true);
}
handsWon = 0;
handsLost = 0;
} //END STAND METHOD
And the condition that helps to meet it is here:
//method to add scores to text fields
public void addScores(int pScore, int dScore, TextField playerNum, TextField dealerNum) {
//ADD PLAYER SCORE
String playerScore = playerNum.getText();
int playerCurrent = Integer.parseInt(playerScore);
int newCurrent = playerCurrent + dScore;
String newScore = Integer.toString(newCurrent);
playerNum.setText(newScore);
//ADD DEALER SCORE
String dealerScore = dealerNum.getText();
int dealerCurrent = Integer.parseInt(dealerScore);
int newDealCurrent = dealerCurrent + pScore;
String newDealScore = Integer.toString(newDealCurrent);
dealerNum.setText(newDealScore);
}
I add the scores to text fields and then pull them again later in the project. Yet, even when the values are meeting the conditions of being larger than the opponents value, the statement does not trigger.
The expected result is when I click on the 'Stand' button, the statement is triggered and then the variable that adds to the total tally is activated.
Try putting System.out in every step to check if it is actually getting there. Put one as the first statement in the Stand method like: System.out.println("In Stand method");
Then put more of those before the if statements and inside them like:
System.out.format("Before: playerFinal : %s, dealerFinal: %s, playerFinal > dealerFinal: %d %n", playerFinal, dealerFinal, playerFinal > dealerFinal);
if (playerFinal > dealerFinal) {
System.out.format("In: playerFinal : %s, dealerFinal: %s, playerFinal > dealerFinal: %d %n", playerFinal, dealerFinal, playerFinal > dealerFinal);
Do that for each of the methods, to see if that method is actually running and what the values are.
If you see that the if statements are executing and the flow going into them, but you don't see any changes on the GUI elements, then try using:
Platform.runLater(() -> {
// Your GUI changes code
playerNum.setText("YOU WIN!");
dealerNum.setText("YOU WIN!");
});
Platform.runLater receives a runnable as an argument, and is the right way to update the GUI if you are using JavaFX.
Sometimes you may save the file and run it and the IDE would not actually compile it, running the old code. In that case, you can try restarting the IDE and trying again.
Related
I've decided to programm a search system for finding students and teachers in a school via GUI. It is an OOP and need some tweaking here and there, but there is one issue which doesn't seem logical to me. When I'm searching for a teacher, I have to type there name or surname into a JTextField and press the Search button which runs a method that loops through an ArrayList of teacher-objects and checks if their names match with the one in the Textfield. Then it checks if these teachers have multiple subjects and grades and it goes through nested if-statements. After the teacher is found, their information is displayed on a GUI with several Texfields. Theoretically if the name I typed into the TextField doesn't match one from the teacher objects, a Error Message should pop-up saying the teacher I'm looking for isn't in the system. But even though I type in the correct name and get all the information displayed, it sends me to the Error Message everytime. I tried to fix it with a break statement but that didn't work either. Can someone please help me with this.
Here is the code I'm talking about:
public void lehrerSuche()
{
String lehrername = tfSuchfeldLehrer.getText();
for(int i = 0; i < td.getFachliste(0).getListenLaengeLehrerListe();i++)
{
if(td.getFachliste(0).getLehrerliste(i).getName().equals(lehrername) || td.getFachliste(0).getLehrerliste(i).getNachname().equals(lehrername))
{
if(td.getFachliste(0).getLehrerliste(i).isMehrerefaecher() && td.getFachliste(0).getLehrerliste(i).isMehrereklassen())
{
tfNameLehrer.setText(td.getFachliste(0).getLehrerliste(i).getName() + " " + td.getFachliste(0).getLehrerliste(i).getNachname());
tfKürzelLehrer.setText(td.getFachliste(0).getLehrerliste(i).getKuerzel() + ".");
tfKlasse_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlasse().getBezeichnung());
tfKlasse_2Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlass2().getBezeichnung());
tfFach_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach().getFachbezeichnung());
tfFach_2Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach2().getFachbezeichnung());
}
if(td.getFachliste(0).getLehrerliste(i).isMehrerefaecher() == false && td.getFachliste(0).getLehrerliste(i).isMehrereklassen())
{
tfNameLehrer.setText(td.getFachliste(0).getLehrerliste(i).getName() + " " + td.getFachliste(0).getLehrerliste(i).getNachname());
tfKürzelLehrer.setText(td.getFachliste(0).getLehrerliste(i).getKuerzel() + ".");
tfKlasse_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlasse().getBezeichnung());
tfKlasse_2Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlass2().getBezeichnung());
tfFach_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach().getFachbezeichnung());
}
if(td.getFachliste(0).getLehrerliste(i).isMehrerefaecher() && td.getFachliste(0).getLehrerliste(i).isMehrereklassen()==false)
{
tfNameLehrer.setText(td.getFachliste(0).getLehrerliste(i).getName() + " " + td.getFachliste(0).getLehrerliste(i).getNachname());
tfKürzelLehrer.setText(td.getFachliste(0).getLehrerliste(i).getKuerzel() + ".");
tfKlasse_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlasse().getBezeichnung());
tfFach_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach().getFachbezeichnung());
tfFach_2Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach2().getFachbezeichnung());
}
if(td.getFachliste(0).getLehrerliste(i).isMehrerefaecher() == false && td.getFachliste(0).getLehrerliste(i).isMehrereklassen()==false)
{
tfNameLehrer.setText(td.getFachliste(0).getLehrerliste(i).getName() + " " + td.getFachliste(0).getLehrerliste(i).getNachname());
tfKürzelLehrer.setText(td.getFachliste(0).getLehrerliste(i).getKuerzel() + ".");
tfKlasse_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlasse().getBezeichnung());
tfFach_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach().getFachbezeichnung());
}
break;
}
else
{
switchPanels_3(panelErrorLehrer);
}
}
}
I've uploaded my project to GitHub. Methods and variables are written in German, so I'm really sorry if you can't understand what I have written. If u have questions please hit me up. I use Eclipse to code.
This link should direct you to my GitHub:
https://github.com/Gonzo-CR/Home-Projects.git
If the link doesn't work, look for Gonzo-CR on GitHub and check out my Home-projects repository where I uploaded all the files.
For better undestanding these are the Object oriented classes:
Person(Abstract)
Schueler
Lehrer
Fach
Schulklasse
Spezial
Sprecher
GUI classes:
Suchsystem
Testdaten(A class which generates all my objects)
The problem is likely that if td.getFachliste(0).getLehrerliste(i).getName().equals(lehrername) is not true the very first time the loop runs, switchPanels_3(panelErrorLehrer); will be triggered - regardless of whether the condition is met on a later iteration of the loop.
What you need is to check a sentinel value after the loop finishes - e.g.:
bool lehrerGefunden = false;
for(int i = 0; i < td.getFachliste(0).getListenLaengeLehrerListe();i++){
if(td.getFachliste(0).getLehrerliste(i).getName().equals(lehrername) || td.getFachliste(0).getLehrerliste(i).getNachname().equals(lehrername)){
//etc.
lehrerGefunden = true;
break;
}
}
if(!lehrerGefunden){
switchPanels_3(panelErrorLehrer);
}
That way, you check every entry in the list before deciding whether to show the error.
I'm trying to code a trivia based game with ActionEvent based buttons. I organized each specific event that is connected to JButton instances in a if-else structure and inside each of these structures, a method would be called. One of these methods would increment a variable that holds the number of the answers that are correct (cor) and wrong (inc):
public void compare(String sel , String ans)
{
//if correct
if(sel.compareToIgnoreCase(ans) == 0)
{
q.setText("Correct! 10 points added!");
score += 10;
cor++;
}
//if incorrect
else
{
q.setText("Incorrect! The correct answer was: " + ans);
inc++;
}
}
This set of code would be run from this:
public void actionPerformed(ActionEvent event)
{
if(e.equals("GUESS"))
{
userGuess = entry.getText();
answer = ans.get(currentQuestionIndex);
base.remove(entry);
base.remove(submit);
submit.setText("OK");
submit.setActionCommand("OK");
submit.addActionListener(this);
base.add(submit);
compare(userGuess, answer);
}
...
}
However, whenever the compare method is called, the inc and cor value seems to increment by an ambiguous value. For example, if I were to answer one question right, the new value for cor would be 2 instead of 1. When I answer another right, cor would be 5 instead of two. I tried using tracers in my code but so far, I appears that the program detects the actionEvent that runs compare() is being pressed multiple times, and as a result, it runs said code multiple times. How can I fix my code so that these variables can be incremented correctly by 1.
submit.addActionListener(this);
Don't add the ActionListener in the actionPerformed() method.
Each time the actionPerformed is invoked you add another listener, so when you click on the "Submit" button you have code that is executed multiple times.
I have a project for my computer science class and we're making battleship. Part of the program is that we have make sure that the piece the player puts down does not go off of the board.
I've made a method to check to see whether it goes off the board:
private static boolean test(String s, int row, int column,int spaces)
{
if(s.equals("right")&&column+5<=10)
{
return true;
}
if(s.equals("up")&&row-spaces>=0)
{
return true;
}
if(s.equals("left")&&column-spaces>=0)
{
return true;
}
if(s.equals("Down")&&row+spaces<=10)
{
return true;
}
return false;
}
But once I've gotten it to print out an error message, I'm not sure how to make it so that the program can re-recieve the new position for the piece, without putting an if statement in and if statement in an if statement (and on and on), because you need to check the new position to make sure it doesn't go off of the board.
Here is the part where I get the position of the playing piece (although I don't think you need it)
Scanner sonic= new Scanner(System.in);
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
int beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
int begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
String direction = sonic.next();
And here's one of the if statements that I use to check/place the pieces
if(direction.equals("left")&&test("left",beginrow,begincolumn,5))
{
for(int i = beginrow; i>beginrow-5; i--)
{
battleship[begincolumn-1][i-1] = ('a');
}
}
else if(!test("left",beginrow,begincolumn,5))
{
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
}
This may be a duplicate, but I didn't know how to reword my search to find what I wanted. (So if anyone could direct me to the right article, that'd be nice as well)
What you should do is split your code appropriately into methods and call that methods repeatedly until your program is satisfied with the outcome.
For example:
create a method startGame() which has the job call methods getting user input until satisfied
make a method to request the user to input all the different ships and other required data
That might look something like
public void startGame() {
// do some setup
while(!requestShipInput()) { // request ship data until the data is valid
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
}
// do some more ship setup
// get the actual playing started
}
public boolean requestShipInput() {
Scanner sonic= new Scanner(System.in);
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
int beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
int begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
String direction = sonic.next();
if(direction.equals("left")&&test("left",beginrow,begincolumn,5)) {
for(int i = beginrow; i>beginrow-5; i--) {
battleship[begincolumn-1][i-1] = ('a');
}
return true; // valid ship data
}
return false; // invalid ship data
}
As a first step, separate input validation from taking the action based on that input - you already have the validation logic in a separate function, so this is easy. Then figure out what needs to be done in case of invalid input - in your case, you need to ask for new input until you get a valid position:
do {
System.out.println("Please input the row where you want the aircraft carrier (5 spaces) to begin: ");
beginrow = sonic.nextInt();
System.out.println("Please input the column where you want the aircraft carrier (5 spaces) to begin: ");
begincolumn = sonic.nextInt();
System.out.print("Please input what direction (up, down, left, right) \nyou want your battle ship to face, making sure it doesn't go off of the board.");
direction = sonic.next();
} while (!test(direction, beginrow, begincolumn, 5))
After that, you know you've got a valid position.
My next step would probably be to group the information required to describe a ship on the board (i.e. beginrow,begincolumn,direction, probably also size) in a separate Object - possibly named Ship.
I think you could pretty naturally use recursion here:
public void getInput() {
// scanner code to get input
if (!test("left",beginrow,begincolumn,5)) { // test failed
getInput()
return
}
// test succeeded, continue
}
You already have something to the limits of you board? If you execute the check first, you don't need to execute a cascade of if-else
if(!test(direction,beginrow,begincolumn,size))
{
System.out.println(" ");
System.out.println("*****ERROR: your piece goes off the board, please re-enter your position and direction*****");
} else {
// check for collision with already placed ships
}
Keep in mind that there is a chance to combine up/down and left/right. The calculation rules are nearly the same and you only have to decide if you have to look to the one or the other direction.
I have a text based game that I am making. It is a RPG style where the user is given options linked to numbers and they have to choose a number. Now my problem is that when running the program. A certain method, Decision(), only works certain times. The method is in a superClass while it is being called in the subclass. in the subclass, It works the first time, but not necessarily the second. Also, when I copy the decision method from the superclass into the subclass its starts working, but the next time it is called, it stops. Here is what I've tried and the results. I've included the decision method and where it is being called.
Decision Method:
public int decision(String question, int length, String[] choices){
int[] numbers = new int[length];
int iterator = 1;
for(int i = 0; i < length; i++){
numbers[i] = iterator;
iterator++;
}
boolean done = false;
while(!done){
//print("Test");
print("");
print(question);
String options = "";
for(int i = 0; i < numbers.length; i++){
options = (options + numbers[i] + " - " + choices[i] + " ");
}
print(options);
boolean univSet = true;
int entry = 1;
while(univSet){
if(univInt != 0){
univSet = false;
entry = univInt;
univInt = 0;
//print("testing");
}
}
if(entry == 23){
help();
}else{
for(int i = 0; i < numbers.length; i++){
if(entry == numbers[i]){
done = true;
univInt = 0;
return entry;
}
}
print("Invalid Number, Try again");
print("");
univInt = 0;
}
}
return (Integer) null;
}
Chapter1 Class (Where it's being called:
public class Chapter1 extends Story implements Serializable {
Player player;
public Chapter1(Player player){
this.player = player;
}
public void engage() {
// TODO Auto-generated method stub
player.chapter = 1;
save(player.name);
sPrint("Welcome to Chapter 1");
print("You wake up in a lighted room with white walls.\nA fresh breeze is coming through the window yet the air smells rotten.");
print("You jolt up suddenly. You don't remember anything about how you got here. You've even forgotten who you are.");
print("You look down at your white shirt, there is a streak of blood across the top.\nYou are wearing a nametag that says: " + player.name + ".");
print("You're sitting in a chair but there are no restraints. You decide to get up and look around");
cur = decision("What do you do?", 2, new String[]{"Try the door", "Look out the window"});
print(cur + "");
if(cur == 1){
print("You walk over to the door and try and open it, it is unlocked.\nYou walk through and are welcomed by a cold and poorly lit hallway");
}else{
print("You walk to the window and look outside. You see a huge barren field. You can make out a humanoid like structure.\nYou call out yet the figure doesn't move.");
print("You decide to try the door. It's unlocked so you walk through into a cold dimly lit hallway.");
}
print("You see a dull knife on the floor as well as a door on the end of the hallway");
cur = decision("What do you do?", 2, new String[]{"Go to the door", "Take the knife"});
if(cur == 2){
print("You pick up the knife.");
addWeapon("Kitchen Knife", player);
}else{
print("You walk down the hallway to the door when suddenly the door opens and out comes a zombie.\nIt Lunges for your shoulder. You are caught by surprise and it bites into your skin and you are infected");
gameOver();
}
print("You continue to walk down the hall when suddenly a hideous creature lunges out from the door.\nYou jump back and prepare yourself for a battle.");
battle("Zombie", 5, 2, player);
sPrint("I see that you have succeeded in your first encounter with the undead.\nI congratulate you but you have a long way to go. Remember, I am your only way to learning about your past. \nNow, make your way down to the bottom of the tower. I will help you where I see fit along the way.");
print("You look around and see that the lights have brightened up. The zombie has been mutilated by your Kitchen Knife. \nYou don't know where the voice came from but you are scared. Behind the zombie's original hiding spot you see a staircase.\nYou follow it down, onto what seems to be..the 11th floor.");
print("");
print("Please input 'complete' to continue");
pause();
sPrint("Chapter 1 complete");
}
Now in this class, engage() is being called to run this chapter. And decision is being called where you see it, as well as in the battle() method(the battle method loops a couple times and decision() is called every loop.
Originally, both Decision and battle are in the superclass, but not in the sub class. This results in the first decision method in the class to be called, but not the second. In the second, it stops at the loop checking the value of univInt.
When I put the decision method into the sub class, It passes the first two but it fails to get past the first one in the battle method for the same reason.
When I put both the decision and battle method into the sub class, it has the same result as just putting decision.
Finally if I put battle in the sub class but not decision it only passes the first two again.
In the project I have one variable named cur that holds the integer value of whatever decision returns. I reuse it for every decision. I don't know if that has anything to do with it. This really doesn't make sense to me how whether the methods are in the same class, or inherited would matter at all if they are the same method.
I am ready to clarify anything and I hope someone is able to understand what is going wrong.
EDIT:
univInt is being set to another number other than 0 outside of decision. thats why it works some times. It is a swing class and a method in a superclass sets univInt to whatever is in a TextField when a button is pressed so with that while loop I try to constantly check to see univInt has been changed from 0
It seems like your "univInt" is a class member, not a local variable, and you do not reinitialize it when entering the function. Thus it won't be changed back to allow the program to enter the if-statement you mention.
Lets say if the last level of a game is beaten then you dont show a dialog box asking if the player wants to go on to the next level, but rather to the mainmenu. SO basically if something happens the things that are supposed to happen afterward dont.
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
final ImageIcon pokeballIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\pokeball5.gif");
final ImageIcon pokemoneggIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\nidoking.gif");
final ImageIcon pokemonredIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\red.gif");
String userAnswer = answertextArea.getText().trim();
if (userAnswer.equalsIgnoreCase(answers.get(questionNumber))) {
answerLabel.setText("Correct");
levelScore ++;
triviagui.totalScore ++;
} else {
answerLabel.setText("Incorrect");
}
answertextArea.setText("");
questionNumber++;
if(questionNumber == questions.size()){
JOptionPane.showMessageDialog(null, "Your score for this level was : " + levelScore + " out of 10. \n Your total score is " + triviagui.totalScore, "Scores",JOptionPane.INFORMATION_MESSAGE, pokeballIcon );
if(difficulty == 3){
JOptionPane.showMessageDialog(null, "Good job you beat the game! \n Your total score was " + triviagui.totalScore + " out of 30.", "Thanks for playing!", JOptionPane.INFORMATION_MESSAGE, pokemonredIcon);
triviagui.questionFrame.setVisible(false);
triviagui.mainFrame.setVisible(true);
}
int leveloptionPane = JOptionPane.showConfirmDialog(null,"Would you like to go on to the next level?" , "Next Level?", JOptionPane.YES_NO_OPTION, levelScore, pokemoneggIcon);
if(leveloptionPane == JOptionPane.YES_OPTION){
difficulty++;
triviagui.questionFrame.setVisible(false);
triviagui.questionFrame=new QuestionFrame(difficulty);
triviagui.questionFrame.setVisible(true);
}
if(leveloptionPane == JOptionPane.NO_OPTION){
triviagui.questionFrame.setVisible(false);
triviagui.mainFrame.setVisible(true);
}
return;
}
updateQuestionScore();
}
You simply want to do:
if(something happens) {
return;
}
If you want to jump out from method use
return;
example of something like that:
public void myMethod(){
if(mynumber==5){
doThis();
}else{
return;
}
/*
*do something else <- this wont be executed if number doesnt equal 5
*cause we are already out of method.
*/
}
If you dont want to jump out from whole method bud only form part of it for instance loop.
break;
example of that:
public void myMethod(String[] stringArr){
for(String s:stringArr){
if(s.equals("hello")){
break; //get me out of this loop now !
}else{
s+="alriight";
}
}
}
doSomethingElse();//this will be executed even if you go thru break; you are still inside method dont forget.You are just out of loop
}
There are better uses for that maybe examples aint best bud you will understand how to use it form this:).
When you use break or return.In eclipse for instance you will be shown Where you actually exit. it will highlight "}"
There are several ways to do this:
You can return from a method.
You can break to exit a loop or continue to start the next iteration of the loop.
You can use an 'else' to only execute other code if the first section did not execute.
You can set a boolean flag variable and then check for that elsewhere in your code.
Depending on what you are trying to do each of these is sometimes the best way, sometimes not the best way.