JOptionPane.showConfirmDialog variable usage - java

So I am very new to this and I am trying to get the variables to add up during the process of the code in order to print the total at the end, in doing so, I need it to read the selection from the JOptionPane that the user entered and add the value to the total at the end. The code is almost complete but is missing the calculation of the variables.
Q: How do I get the value of any variable based on what the user selects from the JOptionPane and add it to the cumulative total to println at the end?
An ex is as follows:
(Sorry if it isn't formatted correctly, I am working on learning how it should look)
int addons = 0;
do{
addons = JOptionPane.showConfirmDialog(null, "Would the customer like to add Salad, Smoothie, Sundae or Cone?");
if (addons == JOptionPane.NO_OPTION);
else if (addons == JOptionPane.YES_OPTION){
String[] choices2 = { "Salad $"+salad, "Smoothie$"+smoothie, "Sundae $"+sundae, "Cone $"+cone};
String extras = (String) JOptionPane.showInputDialog(null, "Which addon?",
"Extras", JOptionPane.QUESTION_MESSAGE, null, // Use
choices2, // Array of choices
choices2[0]); // Initial choice
count++;//Add item to count
System.out.println(extras);
} //close YES_OPTION parameters
} //close do parameters
while(addons == JOptionPane.YES_OPTION); // Exit do while loop6

Related

Is there a way to use Input selection on Joptionpane

I am a first-year computer science student. Coding in java is pretty new to me but I have achieved solutions to some of my problems. I have a question I'm struggling with, it asks me to use JOptionPane as a selection method. I know how to use the default selection dialog box but my question requires me to use JOptionPane to show choices(eg 1, withdraw 2, deposit 3, print details), and then it requires me to press 1, 2 or 3 to run that instruction. I have failed to find a way to input choice please may I be assisted :)`
public String setTown(){
weightSelection w1 = new weightSelection();
String [] towns = {"Durban","Pretoria","Cape Town"};
String input = (String) JOptionPane.showInputDialog(null, "Please select townoption",
"The Choice of a Lifetime", JOptionPane.QUESTION_MESSAGE, null, // Use
// default
// icon
towns, // Array of choices
towns[1]); // Initial choice
choice = input;
System.out.println(choice);
w1.setWeight();`
If you write
String [] towns = {"1. Durban","2. Pretoria","3. Cape Town"};
and the dialog opens the User might only need to press 1 or 2 or 3 on the keyboard.
Because the optionpane has the focus it recieves the keyhits and have a natural behaivor in selecting matching options to that keyhit.
Unfortunately the user have to hit "return" or click "ok" to confirm the selection and close the dialog.
Here is another example you could try
String dialogmessage = "Please choose a dessert";
String[] desserts = {"Cheesecake","Ice Cream","Mousse","Carrot cake"}
String dessert = (String)JOptionPane.showInputDialog(dialogcombo.this, dialogmessage, dialogtitle, JOptionPane.QUESTION_MESSAGE, null, dessert, dessert[0]);
if(dessert == null){
showStatus("You clicked cancel");}
else{showStatis("Your Choice was: " + dessert);}
Hope this helps
Code is running smoothly and has no errors, though my output for t1.choice is null
he is the code
System.out.println("");
System.out.println("Your Recipt" + "\n"+ "**********************" + "\n" + "Town: "+ " " + t1.choice );

if-statements not being triggered when conditions are met

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.

Java: Continuing iteration through an arraylist only when the right menu item is selected

I'm trying to create a console app that iterates through an arrayList of meal ideas every time the correct menu item is selected. The problem is that I can't seem to continue the iteration every time the correct menu item is selected, it just restarts the loop.
Scanner in = new Scanner(System.in);
ArrayList<String> meals = new ArrayList<String>();
meals.add("pasta");
meals.add("potatoes");
meals.add("pork");
String select = "";
while(!select.equals("q")){
System.out.println("What would you like to do?");
System.out.println("\t 1. See next suggestion.");
System.out.println("\t 2. <Another option>");
System.out.println("\t 3. <Another option>");
select = in.next();
switch(select){
case "1":
//Here's where the problem is:
int nextIdea = 0;
while(){
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
break;
}
System.in.read();
break;
}
}
After the user selects to show the daily selection, the first item in the list should be displayed then it should go back to the "What would you like to do menu" then next time the user selects option 1 in the menu it should display the next item in the menu but instead it restarts the loop. I understand it's because the counter variable ("nextIdea") is set to zero every time before the loop executes but how can I get it to remember which arrayList index number was last used and then use that next time the user selects to see the daily meal. The list should only reset to 0 once it's gone through all the items in the list.
Any help would be appreciated, thank you!!
You need to move the nextIdea index out of the first loop. Then you also don't have to iterate the list when the user selects "See next suggestion." - You just display the next idea:
int nextIdea = 0;
while(!select.equals("q")){
System.out.println("What would you like to do?");
System.out.println("\t 1. See next suggestion.");
System.out.println("\t 2. <Another option>");
System.out.println("\t 3. <Another option>");
select = in.next();
switch(select){
case "1":
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
System.in.read();
break;
}
}
So, basically, you don't need the inner loop to iterate over the meal ideas. You already do the iteration with the outside loop: Every time the user selects menu item #1, you show her the next idea.
You should also make sure that nextIdea is always a valid index in the array list. Something like:
case "1":
if(nextIdea >= meals.size()) {
nextIdea = 0;
}
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
System.in.read();
break;
Firstly, instantiate nextIdea outside of the while loop like you have mentioned.
Then, includ a simple if statement which checks if the nextIdea has reached the end, like so:
while(true)
{
if (nextIdea < meals.size())
{
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
}
else
{
nextIdea = 0;
}
break;
}
You didn't have a condition in the while loop, so I'm assuming you meant 'true' which means it'll run infinitely until broken out of.
Although, technically, the loop here isn't really doing anything as it just runs once and breaks out, so you can just get rid of it like so:
if (nextIdea < meals.size())
{
System.out.println("\tToday: " + meals.get(nextIdea));
nextIdea++;
}
else
{
nextIdea = 0;
}
I think you need to think carefully about what it is you actually want to achieve and what the best way to do this is.
Feel free to ask my further questions.

Displaying "Correct" and "Wrong" in JAVA

I'm making a simple quiz program. I need to display my Correct and Wrong it depends on the answer of the user. I think it is in the IF else. That's why I can't get it through. When I run it. I choose the correct answer. It is still displaying "Wrong!" and it counts it as correct. and Then change to different number. It is still displaying "Wrong!". I'm using checkbox as the multiple choice of the quiz.
Here's my code:
if(C1.getState()) // if the user chooses the checkbox c1
{
outputlabel.setText("Correct\n");
CorrectAnswer++; // it will count one point per correct answer.
}else
outputlabel.setText("Wrong!\n");
if(C13.getState()) // if the user chooses the checkbox C13
{
outputlabel.setText("Correct\n");
CorrectAnswer++;
}else
outputlabel.setText("Wrong!\n");
if(C19.getState()) // if the user chooses the checkbox C19
{
outputlabel.setText("Correct\n");
CorrectAnswer++;
}else
outputlabel.setText("Wrong!\n");
if(C21.getState()) // if the user chooses the checkbox C21
{
outputlabel.setText("Correct\n");
CorrectAnswer++;
}else
outputlabel.setText("Wrong!\n");
if(C27.getState()) // if the user chooses the checkbox C27
{
outputlabel.setText("Correct\n");
CorrectAnswer++;
}else
outputlabel.setText("Wrong!\n");
CorrectLabel.setText("Correct Answers: "+CorrectAnswer);
score =(CorrectAnswer*100)/5; // average of the quiz
if (score>=75)
{
scorelabel.setText("Grade: "+score+ "% ");
}else{
scorelabel.setText("Grade: "+score+"%.");
repaint();}
}
}
I'm not entirely sure what you're trying to do in the code. For each you're checking if it is set, and then you're setting the outputlabel value. So if the first checkbox is checked it will set the outputlabel text to "Correct". And if any of the other checkboxes are not checked it will then simply override what you did before and set the label to "Wrong".
Maybe you want separate outputlabels for each of the checkboxes?
You should have one final output label, after you check the state of all the correct answers. And based on the correct answers count, you can set the final output label.

Loops and JOptionpane

I wrote a program that allows the user to enter the Identity Number, Name, Nationality, Job type of the client (ordinary, academician, medical person), Destination country, amount to be transferred in SAR, type of currency to be received (SAR, local currency)and then displays the Identity Number, Name, Nationality, Destination country, Amount to be transferred in SAR, Amount to be received, total amount to be paid by the client I need to know how do I do this : After each program run, I need to ask the user if she wants to continue using the program (using confirmation dialog of JOptionPane). If the user clicks YES, the program will continue and ask the user for another input. This process continues until the user clicks NO ... Please help!
Generally in cases like this I believe you need to loop round until the user selects a no option:
public class SO{
public static void main(String[] args) {
int choice = 0;
do{
choice = JOptionPane.showConfirmDialog(null, "Continue?");
} while(choice == JOptionPane.YES_OPTION);
}
}
Use showConfirmDialog as follows:
int reply = JOptionPane.showConfirmDialog(null, "Are you sure you want to close?", "Close?", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
System.exit(0);
}
use do while loop..
do{
// your all operations...
// finally ask yes or no..
}while(choice.equalsIgnoreCase("yes"));

Categories