JAVA - Menu running in loop - How can I print out all choices? - java

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);

Related

How to alter and display only one column (via user input) on 2D array Java

I am creating a game board. I need it to reveal a the selected column after a user input, while the rest of the columns still print as "X". This game holds values I have set in each column, but does not print them on the screen. When the user selects a column, I need it to print showing the value that column is holding while the rest of the columns still print "X" so they do not reveal what they have. I am new to this, thank you for your help.
This is the function where I think the problem is. If you look, you will see that I have the if statement "if (isCovered) - then I want it to print the covered version. Then the "else" - which is where I want it to print just the one that was guessed as its actual value. I have tried multiple ways of achieving this with no luck. Is there are way to make it like (!isCovered)? But that doesn't work, because it states it needs to be an array and the function "!" does not work. Right now it just seems like it never prints the "else" statement at all. I have functions that take the user input and compare them to "isCovered" and they work correctly, because the piece moves on the board as it should. I just cannot get it to print the actual value instead of an "X". Thank you for any help and if further information would be helpful, please let me know. It is due today unfortunately I only had a few days to work on it and have been working constantly on it.
public static void PrintRevealBoard(int[][] myArray,Boolean[][] isCovered)
{
int i, j;
for (i = 0; i<myArray.length ; i++ ) { // array.length = max rows
System.out.print((i+1) + " ");
for(j = 0; j <myArray[0].length; j++) { // array[0].length = max
cols
if(isCovered[i][j]){
System.out.print(GetRollColorCovered(myArray[i][j]) + " ");
} else {
System.out.print(GetRollColor(myArray[i][j]) + " ");
}
}
your main module is kinda messy. And I don't know how GetRollColor(dice) works. Anyway as I understand you have a two dimensional array and you want to show only a specific value. Seems like u want to show the entire input column.
use this to update isRevealed() after the input of inputCol.
public static Boolean[][] updateRevealed(Boolean[][] isRevealed, int inputCol){
for(int i=0;i<isRevealed[inputCol].length;i++)
isRevealed[inputCol][i] = true;
return isRevealed;
}
update like this,
isRevealed = updateRevealed(isRevealed,inputCol);
your printRevealBoard is almost correct. Just remove the first line. It doesn't make sense and you don't want it as I see
int isRevealed = inputCol;
I don't know how your array looks like. But because of the first for loop u will definitely get an
index out of bounds exception
loop runs until I becomes myarray.length. and in the next loop you access index I of myArray. Exception will be thrown if I=myArray.length. u gotta fix it. If any problem occurs lemme know.
thankyou
edit:
try this for printRevealBoard
public static void printRevealBoard(char[][] myarray , Boolean[] []isRevealed){
for(int i=0;i<myarray.length;i++){
for(int j=0;j<myarray[0].length;j++){
if (isRevealed[i][j]) System.out.print(myArray[i][j] + " ");
else System.out.print("* ");
}
System.out.println();
}
}

Java array in for loop

I'm trying to create a menu for toll data entry that runs in a loop until the user requests to exit. The menu will ask the user to enter data which is stored in an array and keeps adding to the array until the user exits from the menu.
The menu should look as follows:
Toll Data Entry Menu
My menu works fine until asking the user to enter the trip date. The menu will continue to ask for each trip date up until the end of the length of the array (30 - arbitrary length).
I however want the menu to ask for the trip date, store the value entered by the user, then move onto entering the entry point, store value, etc and then loop back to the selection for the user to enter the above details again for a separate trip until they choose to exit. (I need to print these values later on) I'm not sure how to store the values from the user separately without prompting the user to enter all (30) values at the one time.
Should I be using an array or is there another way to store multiple values for a looped menu?
Hope my explanation is clear.
To fetch the complete set of details one at a time, you just need a single for loop as:
String[] datesA = new String [30];
int[] entryP = new int [30];
int[] exitP = new int [30];
for (int i = 0; i < 30; i++) {
System.out.println("Enter trip date: ");
datesA[i] = inputA.nextLine();
// User to enter entry point
System.out.println("Enter entry point: ");
entryP[j] = inputA.nextInt();
// User to enter exit point
System.out.println("Enter exit point: ");
exitP[k] = inputA.nextInt();
}
To improve the implementation though think over the lines of creating an object that includes all the details in one as :
class TollDataEntry {
String entryDate;
int entryPoint;
int exitPoint;
.... getter, setter etc.
}
and then use an array or Collection of this object to store the details of each TollDataEntry with those three values as a single entity.

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.

Trying to add if statement values to the total answer in Java

quite new to Java so trying to understand it can be difficult.
Anyways the problem, as part of a task I have to code a theatre tickets console application. I've almost finished I'm just trying to add the last part
As part of the task we have to ask the user if they want the tickets to be posted, if yes this incurs a charge which will be applied to the total charge. Currently I'm unsure of how to do this. At the moment I am currently working with If and else statements and.. Well you'll see below.
System.out.println ("Do you require the tickets to be posted?\n(£2.34 for post and packing for the entire order)\n(please enter 'Yes' on the next line if you require postage)");
String postinp = scanner.next();
if ("Yes".equals(postinp)){
System.out.println("Postage will be added to your cost" );
}
else
System.out.println("Postage will not be added to your cost");
Well I'm trying to code, if the user enters 'yes' then it adds on the postage charge to the total, but in this section of code I'm unsure how to do that.
Any help would be appreciated. Thanks!
Inside the if-statement all we need to do is add your £2.34 to the total sum being calculated by the program.
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double total = 10.00;
System.out.println("Do you require the tickets to be posted?\n(£2.34 for post and packing for the entire order)\n(please enter 'Yes' on the next line if you require postage)");
if ("Yes".equalsIgnoreCase(input.next())) {
System.out.println("Postage will be added to your cost");
total = total + 2.34;
} else
System.out.println("Postage will not be added to your cost");
}
use scanner.nextLine() insead of scanner.next();
and use "Yes" instead of "Ye"
What I would do is change
if ("Ye".equals(postinp)) {
to
if ("yes".equals(postinp.toLowerCase())) {
That way it won't be case sensitive to what the user inputs, because otherwise they'd have to input Yes exactly.
You can add more code within the then-else blocks of an if statement
if ( "Yes".equals(postinp) )
{
this.cost += 2.34 ; // or whatever it is you need to do
System.out.println("Postage will be added to your cost" );
}
else
{
System.out.println("Postage will not be added to your cost");
}
You seem to need to resolve two things--evaluating the answer and then acting accordingly.
Try this:
String postinp = scanner.next();
if ("Yes".equalsIgnoreCase(postinp)) {
cost += postage;
System.out.println("Postage will be added to your cost" );
}
else {
System.out.println("Postage will not be added to your cost");
}
The if block checks if the result is some form of "yes" without regard to case. Then it assumes that cost and postage variables (floats) are available and initialized from somewhere. In the "yes" case, cost is augmented by postage.
Also, since you are just learning it isn't a big deal, but at some point you might want to consider your postage to be a value consumed from a constant or from a configuration file. Maybe the initial cost can be too.

How to print a set of for-looped arrays in a JOptionPane?

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

Categories