Do -While loops: Java - java

Good Day Everyone,
I've been having a problem with this bit of code for a while now. I'm making a little game and the gist of this little code fragment is that I want to purposefully lock the persons into this pop-up box until they answer yes. However I continuously receive the error message saying that 'while expected'. I've been thinking for about a day now but I cannot figure a way out to answer this question, can someone help me please?
Kind Regards,
Zeno
int choice = JOptionPane.showConfirmDialog(null, "Will you fight?",
"warning", JOptionPane.YES_NO_OPTION);
do {
/ other code /
}
while (choice
!= 0) {
choice = JOptionPane.showConfirmDialog(null, "Will you fight?",
"warning", JOptionPane.YES_NO_OPTION);
}
}
while (ehealth > 0) {
}
}
}

This is a very simple syntax issue, refer to https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html for formatting.
So it might look more like this:
boolean loopedOnce=false;
do {
//execute *other* code once
//and continues to loop through until choice!=0
if(loopedOnce) getFightingChoice(); //Method for JPane code
loopedOnce=true;
} while(choice!=0);
And then continue on in your program with
while(ehealth>0) {
//more code
}

Related

How set a 'timer' before running body from if/else statement?

In android studio, I want to set some kind of 'timer' before the if/else statement runs parts of it's body. In this case the edit1.setText("") and edit1.setBackgroundColor(Color.parseColor("#FFFFFFF")); Is there a way to do this.
Thanks in advance, have a nice day!
EDIT: I'm not using any UI libraries.
public void check1(View view) {
uinput = edit1.getText().toString();
if (uinput.equals(answerList[0])) {
edit1.setBackgroundColor(Color.parseColor("#00FF00"));
score++;
score_view.setText(String.valueOf(score));
// I only want to delay the three below.
view1.setText(questionList[1]);
edit1.setText("");
edit1.setBackgroundColor(Color.parseColor("#FFFFFF"));
} else {
edit1.setBackgroundColor(Color.parseColor("#FF0000"));
wrong++;
wrong_view.setText(String.valueOf(wrong));
// I only want to delay the three below.
view1.setText(questionList[1]);
edit1.setText("");
edit1.setBackgroundColor(Color.parseColor("#FFFFFFF"));
}
}

Someone have a look at my source code for a number guessing game that seems to keep failing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hello please may someone run my code and assist me in debugging it. I'm having a lot of troubles trying to figure it out and i have not a lot of guidance when it comes to coding.
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
reccomendations to fix it. Thanks in advance
a brief of what i'm trying to do:
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
import javax.swing.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
/*
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
recomendations to fix it. Thanks in advance
*/
enterScreen();
if (enterScreen() == 0){
number();
userIn();
answer();
}
}
public static int enterScreen (){
String[] options = {"Ofcourse", "Not today"};
int front = JOptionPane.showOptionDialog(null,
"I'm thinking of a number between 0 and 100, can you guess what is is?",
"Welcome",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, options, "Yes" );
if(front == 0){
JOptionPane.showMessageDialog(null, "Goodluck then, you might need it. :D");
}
else {
JOptionPane.showMessageDialog(null, "okay i dont mind");
}
return front;
}
private static int number(){
double numD;
numD = (Math.random() * Math.random()) * 100;
int numI = (int) numD;
System.out.println(numD);
return numI;
}
private static int userIn(){
String userStr = JOptionPane.showInputDialog("What number do you think im thinking of?");
int user = Integer.parseInt(userStr);
return 0;
}
private static void answer(){
// here is the problem
if(userIn() == number()){
JOptionPane.showMessageDialog(null, "Well done! You must be a genius.");
}
else {
JOptionPane.showMessageDialog(null, "Shame, TRY AGAIN!");
userIn();
}
}
}
Your problem is this part:
enterScreen();
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You can leave out the first enterScreen(). Because you call it again in the if statement. If you look at the return type of the method: public static int, it returns and int. This makes it so that the outcome of the method is directly available in the if statement. The fist enterScreen is basicly useless, because you dont use the result.
You could do this:
int num = enterscreen();
if (num == 0) {
number();
userIn();
answer();
}
Which is basicly the same as:
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You call enterScreen() twice. Just call it once, and compare the value returned only once.
Also, StackOverflow typically is not for "Here's my code, fix it" kind of not questions.
https://stackoverflow.com/help/how-to-ask
You call enterScreen() and userIn() functions twice or more. Please Computer Science and coding. Hint: Computer's execute intructions from top to bottom.

Can I use IF statements with a message dialog in java?

So, I've been stumped on this piece of code for about a week now, I want to have the code sending an error message when the user chooses 'No' or 'Cancel' however I get an error which tells me that NO and CANCEL are not variables. Does anyone have any suggestions as to how I can overcome this problem?
int mc = JOptionPane.QUESTION_MESSAGE;
int bc = JOptionPane.YES_NO_CANCEL_OPTION;
int ch = JOptionPane.showConfirmDialog (null, "Select:", "Title", bc, mc);
if (bc == NO)
{
JOptionPane.showInputDialog("Sorry, you cannot continue without agreeing to the rules.");
}
else if (bc == CANCEL)
{
JOptionPane.showInputDialog("Sorry, you cannot continue without agreeing to the rules.");
}
else
{
JOptionPane.showInputDialog("Thank you, you may continue!");
}
This is all explained in the JOptionPane Javadoc.
In the code that you've given, the button that you've clicked is identified by the return value from showConfirmDialog, which you've assigned to ch, not bc. In your case, the logic should be
if (ch == JOptionPane.NO_OPTION) {
...
}
else if (ch == JOptionPane.CANCEL_OPTION) {
...
}
else {
...
}

Using JOptionPane.YES_NO_OPTIONS

Here's my problem, I'm trying to get this bit of code to work so that in my GUI, when I click on yes, the product is added (that bit of code is still to be developed) and the addproductwindow closes, but when no is clicked the JOptionPane closes, but the add product window remains open.
(the System.out.print(" no ");) was me just testing what came out from the inputs.
#Override
public void actionPerformed(ActionEvent e) {
int dialogButton = JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog (null, "Do you want to add Product: ","Confirmation",dialogButton);
if (dialogButton == 1){
System.out.println(" no ");
} else {
addProductWindow.dispose();
}
}
When using JOptionPane.showConfirmDialog (...) you need to check which button was clicked by the user.
The basic code is:
int result = JOptionPane.showConfirmDialog (...);
if (result == JOptionPane.YES_OPTION)
// do something
Read the section from the Swing tutorial on How to Use Dialogs for more information and working examples.
if (dialogButton == 1)
Don't use "magic numbers". Nobody knows what "1" means. The API will have variable for you do use that are more descriptive.
For addProductWindow to close, you have to call addProductWindow.dispose() method in the if block too.
#Override
public void actionPerformed(ActionEvent e) {
int dialogButton = JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog(null, "Do you want to add Product: ", "Confirmation", dialogButton);
if (dialogButton == JOptionPane.YES_OPTION) {
addProductWindow.dispose(); // you forgot this
} else {
System.out.println(" no ");
addProductWindow.dispose();
}
}

How to write code that if something happens nothing else happens afterward?

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.

Categories