Method calling and display issue - java

I am new to java and the coding is probably sloppy so please don't be harsh! Anyways, I am making a method that will set increase in turn by 1 each time I hit the end turn button.
public int turns (int turn){
int turns = 0;
if (turn == 0){
btnYes.setEnabled(false);
btnNo.setEnabled(false);
btnRolldie.setEnabled(true);
btnPurchase.setEnabled(true);
btnMove.setEnabled(true);
turn++;
}
if (turn == 1){
btnYes.setEnabled(false);
btnNo.setEnabled(false);
btnRolldie.setEnabled(true);
btnPurchase.setEnabled(true);
btnMove.setEnabled(true);
turn++;
}
if (turn == 2){
btnYes.setEnabled(false);
btnNo.setEnabled(false);
btnRolldie.setEnabled(true);
btnPurchase.setEnabled(true);
btnMove.setEnabled(true);
turn++;
}
if (turn == 3){
btnYes.setEnabled(false);
btnNo.setEnabled(false);
btnRolldie.setEnabled(true);
btnPurchase.setEnabled(true);
btnMove.setEnabled(true);
turn = 0;
}
return(turns);
}
private void btnEndTurnActionPerformed(java.awt.event.ActionEvent evt) {
int turns = 0;
lblturn.setText("" +turns(turns));
When I run the program, the label constantly repeats 0 whenever I hit the button. I was thinking that int turns; would work, but the variable isn't initialized. I do not know if there is an error in my method, or if the initialization in the button is overriding the method.
As I said, i'm new to java so this might be the entirely wrong approach, and if it is, please give me some recommendations on how to improve this kind of structure. Thanks!

int turns = 0; on the second line is a local variable so the value get reset every time the method is called. You need to make it as a field of a class so that it can be shared between method. And also change turn++ to turns++.

You should be having turns++ not turn++

Related

How do I check an array's bounds and make sure the code does not error in the game "Go" that I am making in Java

protected void pressedOnSpace(int row, int col) {
if (board[row][col] < board[0][0]) {
canvas.errors = false;
}
if (board[row][col] == GoFrame.WHITE) {
board[row][col] = GoFrame.BLACK;
}
else if (board[row][col] == GoFrame.BLACK) {
board[row][col] = GoFrame.EMPTY;
}
else if (board[row][col] == GoFrame.EMPTY) {
board[row][col] = GoFrame.WHITE;
}
}
I am making the game "Go" for a Java assignment. This is a helper method I'm having issues on. The game is based on arrays and loops. The instructions tell me that I am supposed to implement a bound check and there is a boolean variable "canvas.errors" and if it evaluates to true, a big "X" appears over the board, false is there's no "X". I am supposed to do an array bound check to make sure the "X" does not appear but I am unsure how to go about it because everything I have tried continues to produce an "X" when I click on the board outside of the bounds of the array. I know I am supposed to find all the possible ways the program could error and evaluate those ways to "false" with the variable/function but I cant seem to figure it out. The first "if" statement is what I have as of now for the bound checker after a bunch of tries. Any help would be appreciated as I am a newer coder.
I think maybe you just need help structuring your code to perform a very common operation referred to as validation, or in plain English, making sure you handle situations where your user submits invalid information. All you want to do is make sure the X and Y values represent a legitimate cell on your goban so that your code doesn't choke later on when it tries to process an invalid value.
protected void pressedOnSpace(int row, int col) {
if (row >= 0 && row < 20) && (col >= 0 && col < 20) {
// insert your logic for changing color
} else {
// insert your logic for drawing a big fat X over the board
}
}

Random number guessing game with limitations after each guess

I am making a number guessing game:
The computer generates a number inside an interval
I try to guess it and receive a reply whether it's higher/lower than my guess or equals to my guess and I've won
There is an interval in which I can guess, as well as a guess attempt limit
The trick is, however, that I need to implement another condition: each guess should "shrink" the interval in which I'm able to guess. For example: computer generates 50, I guess 25, computer replies "The random number is larger.". Now knowing that, I should not guess anything lower than 25 again, it's unreasonable. In case I guess i.e. 15, the computer should reply "The guess doesn't make sense.". I understand that I somehow need to save each guess value to a new variable, but nothing seems to work. I'm a beginner, please bear with the following code, I've tried a lot of things:
public String guess(int guess)
{
int lowerBound = 0;
int upperBound = 99;
Set<Integer> lowerGuesses = new TreeSet<>();
Set<Integer> higherGuesses = new TreeSet<>();
if (gameOver) {
return "The game is over.";
}
if (guess < 0 || guess > 99) {
return "The guess is out of bounds.";
}
if (guessCount < maxGuessCount) {
if (guess < secretNumber) {
if (lowerGuesses.contains(guess)) {
return "The guess doesn't make sense.";
}
else {
guessCount++;
lowerBound = guess;
lowerGuesses.add(guess);
return "The random number is larger.";
}
}
if (guess > secretNumber) {
if (higherGuesses.contains(guess)) {
return "The guess doesn't make sense.";
}
else {
guessCount++;
upperBound = guess;
higherGuesses.add(guess);
return "The random number is smaller.";
}
}
if (lowerGuesses.contains(guess)) {
return "The guess doesn't make sense.";
}
if (higherGuesses.contains(guess)) {
return "The guess doesn't make sense.";
}
}
if (guess < lowerBound || guess > upperBound) {
return "The guess doesn't make sense.";
}
if (guessCount == maxGuessCount) {
gameOver = true;
victorious = false;
return "Ran out of guess attempts.";
}
guessCount++;
gameOver = true;
victorious = true;
return "You won.";
}
Thank you in advance!
First, to avoid confusion, let's rename the method in order to make sure that its name is not an exact match with its parameter, so this is how it should look like:
public String makeGuess(int guess)
avoid naming different entities in the same name space with the exact same name (local variables being present in different methods or parameters having similar names with data members for the purpose of initialization are an exception). From now on, you will call the method as makeGuess(25), for example.
Now, to the actual problem. You have an incorrect assumption. You assume that you need to keep track of past intervals. That's not the case. You can just change the edges of the intervals. Also, your code is superfluous, I advise you to refactor it. Finally, you always initialize upper bounds, local bounds and higher and lower guesses as local variables, so they will never be kept track of. Instead of this, you need to perform the following simple measures in order to make this work:
Define the bounds and limit as data members
protected int lowerBound = 0;
protected int higherBound = 99;
protected int lb = 0;
protected int hb = 99;
protected int limit = 5;
protected int guessCount = 0;
protected int randomizedNumber; //Initialize this somewhere
Note that I have hard-coded some values. You might want to make this dynamic with initialization and stuff like that, but that's outside the scope of the answer. lowerBound, higherBound, limit are game settings. while lb, hb, guessCount represent the game state. You could separate this logic into another class, but for the sake of simplicity, even though I would program differently, I will leave them here in this case.
Have a method that initializes the game
public void initialize() {
lb = lowerBound;
hb = higherBound;
guessCount = 0;
}
So you separate your concern of game initialization from the outer logic of starting and maintaining a game.
Implement makeGuess in a simplistic way
public String makeGuess(int guess) {
if (++guessCount >= limit) return "The game is over.";
else if ((lb > guess) || (hb < guess)) return "The guess doesn't make sense";
else if (randomizedNumber == guess) return "You won.";
else if (guess < randomizedNumber) {
hb = guess;
return "The random number is smaller.";
} else {
lb = guess;
return "The random number is larger.";
}
}
NOTE: I dislike mixing up the logic with the output layer, the reason I did it in the method above was that you have mentioned you are a beginner and my intention is to make this answer understandable for the person who just begun programming and is very confused. For the purpose of actual solutions, you should return a state and in a different layer process that state and perform the console/UI operations you need. I will not go through the details now, as it would also be outside of scope, but for now, please have some success with the solution above, but THEN you should DEFINITELY look into how you need to code, because that is almost as important as making your code work.

Why does nothing happen when a "if ... <=0" criteria is met?

I have a player controlled object which is set to 100 health. With each hit from an enemy it goes down. The problem is, after it reaches 0 health, it still keeps going further into the negatives. I have a popup set
private void playerHealth(){
if (player.health <= 0)
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
so that in theory, it should pop up after health is <=0. However, when I try to run it, it just opens and closes immediately. I can see the window for a split second. If I delete the
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
and replace it with say,
player.isAlive = false;
(isAlive is set true for player, enemies and all bullets), the health will continue to decrease past the negatives.
This part might help as well: Its the code to delete the dead enemies and bullets, there is nothing similar for player, so that may be the problem.
private void removeDead(){
for (int i = 0; i <bullets.size(); i++){
if (bullets.get(i).isAlive == false )
bullets.remove(i);
}
for (int i = 0; i <mobs.size(); i++){
if (mobs.get(i).isAlive == false )
mobs.remove(i);
}
for (int i = 0; i <mobBullets.size(); i++){
if (mobBullets.get(i).isAlive == false )
mobBullets.remove(i);
}
bullets.trimToSize();
mobs.trimToSize();
mobBullets.trimToSize();
}
So any help is appreciated. Thank you. (all the code is from an online tutorial, which is why I dont know anything.)
If you want both statements to be executed, surround them in a block :
private void playerHealth() {
if (player.health <= 0) {
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
}
Without the curly braces, System.exit(0); is not part of the if statement and will always be executed, which explains the it just opens and closes immediately.
I agree with the previous answer.
However, you need to know how to avoid such problems in the future. Use an IDE or other editor that will automatically indent your code for you. Here is what one did to the failing if-statement:
private void playerHealth() {
if (player.health <= 0)
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
The problem becomes much more obvious.
It looks like you missed a { on your if statement, if you want to execute a block of code in an if statement you need to do
if(something){
response;
}
So it should be this:
private void playerHealth() {
if (player.health <= 0) {
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
}

Program freezing on run

I am trying to create a program that works as a "math help calculator" and it asks you questions. I have a button on the calculator to ask you a new question and I want to be able to ask a maximum of ten questions. So I figured why not make a for loop where the button to ask a new questions makes the increment which will then prompt the new question. PROBLEM: for some reason unless I make it i++ in the for loop it's self. My program freezes. No syntax or run time errors but the java program freezes. I guess in theory it would work but I am doing something wrong?
for(int i = 0; i < 10;){
if(e.getSource() == cmdNew){
i++;
}
Your increment is in the incorrect place.
for(int i = 0; i < 10; i++) {
if(e.getSource() == cmdNew) {
}
}
You are in an infinite loop. (e.getSource() == cmdNew) is never true so i never gets incremented and you just loop forever.

Java - Returning strings

I wish to return a string from a method object that is called by another method in another class. My problem is: when I attempt to assign the returned value to a String in the other class, it cannot find the method object within the class object.
Guessing Game = new Guessing();
This makes the object using the class Guessing.Java
else if (buttonObj == guess){
double g = yourGuess.getNumber();
if ((g > 0)&&(g < 11)){
Game.StartGame(g);
label3.setVisible(false);
yourGuess.setEnabled(false);
label1.setText(Game.StartGame());
}else{
label3.setVisible(true);
yourGuess.requestFocus(true);
}
}
When I try retrieving the String from the StartGame method within the Guessing.Java class, it says it cannot find the class.
public String StartGame(double guess){
int round = 1;
int guesses = 3;
String correct = "correct";
if (guesses > 0){
if (guess == ans){
correct = "correct";
}else if ((guess == ans - 1)||(guess == ans + 1)){
correct = "hot";
guesses--;
}else if ((guess == ans - 2)||(guess == ans - 2)){
correct = "warm";
guesses--;
}else{
correct = "cold";
guesses--;
}
}else{
correct = "round";
}
return correct;
}
I have tried several different things and looked it up multiple times but nothing works, can anyone help?
First of all fix your code by using these Naming Conventions.
Change your code to this,
if (buttonObj == guess){
double g = yourGuess.getNumber();
if ((g > 0)&&(g < 11)){
String startGameStr = Game.StartGame(g);
label3.setVisible(false);
yourGuess.setEnabled(false);
label1.setText(startGameStr);
}else{
label3.setVisible(true);
yourGuess.requestFocus(true);
}
}
It is hard to tell what is causing the "class not found" exception with the details given.
But one thing I could see it : You are calling the method as:
label1.setText(Game.StartGame());
But the method expects a double argument.
according to the first code segment there two overloaded methods in Guessing class
StartGame(Double g)
StartGame()
seems to be like you are calling the second method when you try to assing the returned string to that label which probably retuning emty string or since that method doesn't exist you get method not found exception.

Categories

Resources