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 );
Related
I'm trying to learn JAVA and I'm working on a simple pizza order assignment running purely in text/console format.
I've made the user chose a pizza, but they need the option to add extra ingredients.
My thought was to use a for loop to show a toppings menu and then ask for a numbered input matching the ingredient they want to add.
I want them to be able to select several ingredients, why I'm doing it in a loop.
My code as of now looks like this:
for (int i = 0; ingredientInput>0; i++ ){
toppingsMenu();
ingredientInput = ingredientScan.nextInt();
ingredientScan.nextLine();
System.out.println("Type your choice here:");
}
System.out.println(ingredientInput);
Everything works great, but I'd like to add a system.out.println() telling the user, what they've chosen as:
"You've added extra cheese - Would you like to add more?"
If so, I would like to expand that sentence: "You've added extra cheese & pepperoni - Would you like to add more?"
Could you help me by pointing me in a direction that might work? I'm not into any object related part of JAVA yet, purely text-based so far.
Thanks.
Solution provided by Adeel Ahmad
ArrayList<Integer> ingredients = new ArrayList<>();
for (int i = 0; ingredientInput>0; i++ ){
toppingsMenu();
ingredientInput = ingredientScan.nextInt();
ingredientScan.nextLine();
ingredients.add(ingredientInput);
System.out.println("Type your choice here:");
}
System.out.println(ingredientInput);
Looking back it's so interesting to see which problems I struggled to solve, as now, a few months later, this seems so basic. But thanks anyway to everyone who helped :D
First off, you need to be able to store all the added ingredients in data container (e.g ArrayListor HashMap). Whenever user inputs an ingredient, just added that in your ArrayList
ArrayList<Integer> ingredients = new ArrayList<>();
for (int i = 0; ingredientInput>0; i++ ){
toppingsMenu();
ingredientInput = ingredientScan.nextInt();
ingredientScan.nextLine();
ingredients.add(ingredientInput);
System.out.println("Type your choice here:");
}
System.out.println(ingredientInput);
Once you have collected all the user selected ingredients in your ArrayList, you can then iterate over it in a loop and construct your final message.
You could use something like this
String orderedSoFar = "";
boolean done = false;
do {
// read next ingredient from user
String currentIngredient = scanner.nextLine();
// if first extra ingredient
if(orderedSoFar.equals("")){
orderedSoFar += currentIngredient;
// if not first extra ingredient
} else {
orderedSoFar += " & " + currentIngredient;
}
System.out.println("Ingredients so far " + orderedSoFar);
System.out.println("Add more extra ingredients?");
// read choice to continue or not from user
done = Boolean.valueOf(scanner.nextLine());
}while(!done);
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
Consider the following code. For some reason, even after hitting the NO button, it's exiting the do while loop. I recently introduced the recentPurchaseAmount variable and it stopped working after that. Even removing that is not making it work now.
Variables like purchaseAmount , recentPurchaseAmount are double type initialized to 0.0. itemNo, itemCheck are integer type variables.
do {
purchaseAmount = Double.parseDouble(JOptionPane.showInputDialog(
"Enter the Item Purchase Amount"));
recentPurchaseAmount = recentPurchaseAmount + purchaseAmount;
if (onepty.budgetAmountVerify(recentPurchaseAmount)) {
itemNo++;
itemCheck = JOptionPane.showConfirmDialog(null,
"Finished Purchasing Items Purchase Amount?",
"Say Yes or No", JOptionPane.YES_NO_OPTION);
remainingBal = onepty.remainingBalance(recentPurchaseAmount);
}
} while(itemCheck == JOptionPane.YES_OPTION);
JOptionPane.showMessageDialog(null,
"Total items purchased are " + itemNo +
"\n and the remaining balance is : " +remainingBal+"" ,
"This is the Title",JOptionPane.INFORMATION_MESSAGE);
while(itemCheck == JOptionPane.NO_OPTION);will be a more suitable condition.
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.
This was my original code to print out the information entered into the program, it was designed to create a nice little table displaying tutor names on the left with their pay on the right, and the total pay of all at the bottom:
System.out.println("Tutor Stipend Report");
System.out.println("Tutors\t\tPay");
System.out.println("------\t\t---");
for(int out=0;out<numOfTutors;out++) {
System.out.println(names[out]+"\t\t"+stipend[out]);
}
System.out.println("--------");
System.out.println("Total: " +sum);
Now I need to turn this code to display in JOptionPane and here is where I am stuck. I want to keep the same table setup as before but every time I go to display the information, lets say I need to display 3 tutors, it will just come up with 3 JOptionPane dialog boxes instead of printing the 3 tutors in one dialog box.
I realize the problem is because all the information is inside the for loop, but how do I resolve this issue so I can display the designated number of tutors and pay on one dialog box like I had with the System.out.println solution?
for (int out=0;out<numOfTutors;out++) {
JOptionPane.showMessageDialog(null,
"Tutor Stipend Report" +
"\nTutors Pay" +
"\n--------- -----" +
"\n"+names[out]+" "+stipend[out] +
"\n--------" +
"\nTotal: " +sum);
}
You need to move the call to JOptionPane.showMessageDialog outside of the for-loop.
Check out StringBuilder. It's helpful for this sort of thing:
StringBuilder sb = new StringBuilder();
sb.append("There are ").append(count).append(" people in the following list:\n");
for (int i = 0; i < count; i++) {
sb.append("Person #").append(count).append('\n');
}
JOptionPane.showMessageDialog(null, sb.toString());
The problem is since you're calling JOptionPane.showMessageDialog inside the loop, it will execute 3 times. What you should do instead is concatenating the string you want to print into one string object like this:
String toBeDisplayed = "";
for(int out=0;out<numOfTutors;out++) {
toBeDisplayed += /*.. add your string here.. */;
}
JOptionPane.showMessageDialog(null, toBeDisplayed);
Note that cocatenating string using += is not the most efficient thing to do -- consider using StringBuilder / StringBuffer