I'm writing a program for a slot machine simulator and most of my code is in a while loop.
System.out.println(" * Choose an option: * ");
System.out.println(" * 1: Display credit count. * ");
System.out.println(" * 2: Play Again. * ");
System.out.println(" * 3: End Game. ");
If the user selects 3 to end the game, he is directed to the end game menu.
There is a seprate group of if statements outside of my while loop to determine if the user has left the loop because he is out of credits or he has selected to end game.
//The case in which the user ended the game.
else {
System.out.println("");
System.out.println("You have ended the game. You have finished with a total of: "+credits+" credits!");
System.out.println("");
System.out.println("Next player?");
System.out.println("");
System.out.println("1: Yes, there is another player that would like to start with my "+credits+" credits.");
System.out.println("2: Yes, there is another player, but he will start with 10 credits.");
System.out.println("3: No, End the game.");
selection2 = in.nextInt();
}
What I'm trying to do is: if the user inputs 1, it takes him back to the beginning of the main game loop.
I understand there isn't a goto cmd, so does anyone have an idea of how I could do this? I'm stuck outside a loop and can't get back in! (I've thought about making another loop outside of everything...)
What you could do is create a method called goToLoop()
Inside of that method you place all the code of the loop, so when you want to go back to the loop you simply call goToLoop()
I hope that helps
Here is some incomplete code to give an idea of the state pattern.
interface IState {
void action();
}
class InitialState implements {
void action()
{
System.out.println("");
System.out.println("You have ended the game. You have finished with a total of: "+credits+" credits!");
System.out.println("");
System.out.println("Next player?");
System.out.println("");
System.out.println("1: Yes, there is another player that would like to start with my "+credits+" credits.");
System.out.println("2: Yes, there is another player, but he will start with 10 credits.");
System.out.println("3: No, End the game.");
selection2=in.nextInt();
switch (selection2)
{
case 2:
currentState = new OtherGameState();
break;
}
}
}
Don't exit the loop in the first place...
enum Menu {START, MAIN, EXIT, ETC}
Menu menu = Menu.START;
boolean running = true;
while ( running )
{
switch ( menu )
{
case START:
// show and handle start menu here
// As an extra note, you could/should create methods for each menu (start, main, ...)
// Then call these methods from within the case statements
break;
case MAIN:
// show and handle main menu here
menu = Menu.EXIT; // This is an example of how to "change" menus
break;
case EXIT:
// show and handle exit menu here
running = false; // will cause the execution to leave the loop
break;
case ETC:
// ... etc ...
break;
}
}
Related
I need to create a code using java.
When any person enters this beverage shop, it shows how to select and order the menu items and quantity. After selecting one menu, code asks "Do you want to select another menu item". If you don't want another menu enter (-1). After entering (-1) price calculate through the code.The balance is over 1000/= the shop gives 10% discount. The service charge(20%) and VAT(12%) must be added to the balance.
I have created a java code but it does not stop when user enter(-1) and I selected any one menu with one quantity, it shows the balance is 0.0
What is the error of my code.
Scanner scan=new Scanner(System.in);
int i=0;
double tot=0,price,vat,service,res=0,result;
System.out.println("\t\t\t\tWELCOME TO BEVERAGE SHOP");
System.out.print("User Name:");
String name=scan.next();
System.out.println("Hello!!!"+" "+name+" "+"Welcome...");
System.out.print("\n");
System.out.println("Please see our menu and select");
System.out.print("\n");
System.out.println("|\tPRODUCT ID\t|\t\tPRODUCT NAME\t\t|\tPRICE(LKR)\t|\n|\t1\t\t|\t\tTea\t\t\t|\t80\t\t|\n|\t2\t\t|\t\tCoffee\t\t\t|\t100\t\t|\n|\t3\t\t|\t\tIce Coffee\t\t|\t150\t\t|");
System.out.print("\n");
System.out.println("If you have selected the items you want,you can enter the product below");
while(i>=0){
System.out.print("Product Id:");
int id=scan.nextInt();
System.out.print("Qyantity:");
double quan=scan.nextDouble();
System.out.println(id +":"+quan);
System.out.print("if you want to stop entering id and buy, please enter \"(-1)\" \nor you want to continue enter anothe number:");
int no=scan.nextInt();
if(no==-1){
vat=(res*12)/100;
service=(res*20)/100;
result=vat+service;
System.out.println("Your Amount is:"+" "+result);
if(res>1000){
price=(res*10)/100;
vat=(res*12)/100;
service=(res*20)/100;
result=(vat+service)-price;
System.out.println("Your Amount is:"+" "+result);
}
}
else{
switch(id){
case 1:
tot=80*quan;
break;
case 2:
tot=100*quan;
break;
case 3:
tot=150*quan;
break;
}
res+=tot;
}
}
i++;
}
}
while(i>=0){
This line checks whether you'll continue or not. It only checks i.
i++;
this is the only line where I see you alter the value of i. Now, in order to get to that line, i has to be > 0.
Guess what (i+1) > 0 will return?
There's your endless loop.
You'll need to change
i++;
into i= scan.nextInt();
or check other variables.
I will shorten this:
int no=scan.nextInt();
while(i>=0){
//your code
int no=scan.nextInt();
if(no==-1){
//your code
// leave the loop
break;
}
}
you need for the exit / break condition and then leave the while - loop
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.
I have hit another obstacle in my attempt to create a shape calculator and this time it's using a Loop with my Switch/Case statements allowing the user to select the shapes they wish to calculate.
I am trying to make my Calculator like this. User selects 1 for Triangle, they calculate that and say they now wish to select 5 to calculate a Circle right after, then do another circle calculation again and for however many times they wish and then be able to move onto another shape. Say 6 for a sphere.
So far I've tried using a While (True) loop but it seems once I have made a selection I get stuck in that case and can't go on to select another shape to calculate or select the case that closes/exits the program.
I've reduced my program to an example below cutting out the code needed to make a shapes as the shapes themselves are not the program here. It's trying to make my users range of choice flexible I guess you could say.
Scanner scan = new Scanner(System.in); //take user input
int decision = scan.nextInt();
loop: while (true) {
switch (decision) {
case 1:
//example
break;
case 2:
//example and so on
break;
case 3:
break;
case 9:
// Quit
System.out.println("You decided to Quit");
break loop;
default:
// Wrong decision
System.out.println("Select a number between 1 and 8 to make a decision or 9 to Quit");
}
//exit program code here
}
In your loop you need to prompt for and read the next selection. The code you show reads one selection to set decision, but never changes it after that.
Move the scan.nextInt() inside the loop
loop: while (true) {
int decision = scan.nextInt();
switch (decision) {
case 1:
//example
break;
case 2:
//example and so on
break;
case 3:
break;
case 9:
// Quit
System.out.println("You decided to Quit");
break loop;
default:
// Wrong decision
System.out.println("Select a number between 1 and 8 to make a decision or 9 to Quit");
}
//exit program code here
}
Problem:
You are taking decision input only once, since it is written outside the infinite while loop. Therefore during execution of infinite loop, decision will never change and every time same case will get executed, giving an impression that program is stuck within a case, which is not the case any ways.
Solution: Move the input statement withing infinite while loop.
while (true) {
int decision = scan.nextInt();
//rest of the code
....
....
}
You must read the decision input everytime (infinite loop)
This should work:
Scanner scan = new Scanner(System.in); //take user input
loop: while (true) {
int decision = scan.nextInt();
switch (decision) {
case 1:
//example
break;
case 2:
//example and so on
break;
case 3:
break;
case 9:
// Quit
System.out.println("You decided to Quit");
break loop;
default:
// Wrong decision
System.out.println("Select a number between 1 and 8 to make a decision or 9 to Quit");
}
//exit program code here
}
I am trying to make a paint dispenser simulation prototype console application with java. searched everywhere and can't seem to find out why this code won't work. I use netbeans. what I'm trying to do with this code is to display the menu, ask user for input, when user inputs a number it selects that option from menu and then I need to start getting those options to work once I have the menu working. Any help is appreciated thanks. My code so far is shown below.
package paintdispensersimulation;
import java.util.Scanner;
/**
*
* #author Kris Newton (M2124910)
*/
public class PaintDispenserSimulation //
{ //Open Public Class
public static void main(String[] args) //
{ //Start Main
Scanner in = new Scanner (System.in); //
int option; //
boolean quit = false; //Declare variables
do //
{ //Start Do
System.out.println("Please Make a selection:"); //
System.out.println("[1] Process New Job(Decimal Values)"); //
System.out.println("[2] Process New Job(RGB Hexadecimal Values)"); //
System.out.println("[3] Calibrate Dispenser"); //
System.out.println("[4] Display Summary Of Jobs"); //
System.out.println("[0] Exit"); //Print Menu
option = in.nextInt(); //Declare User Input
switch (option) //Declare Switch
{ //Start Switch
case 1: //If Option = 1
System.out.println("You Chose To: Process New Job(Decimal Values)"); //Print
break; //Break
case 2: //If Option = 2
System.out.println("You Chose To: Process New Job(RGB Hexadecimal Values)"); //Print
break; //Break
case 3: //If Option = 3
System.out.println("You Chose To: Calibrate Dispenser"); //Print
break; //Break
case 4: //If Option = 4
System.out.println("You Chose To: Display Summary Of Jobs"); //Print
break; //Break
case 0: //If Option = 0
quit = true; //Quit
break; //Break
default: //If Option Invalid
System.out.println("Selection Invalid: Please enter a valid selection."); //Print
} //End Switch
} //End Do
while (!quit); //While Quit = True
System.out.println("You Chose To: Exit"); //Print
} //End Main
} //End Public Class
This is the message I get when trying to run.
run:
java.lang.VerifyError: Constructor must call super() or this() before return in method paintdispensersimulation.PaintDispenserSimulation.<init>()V at offset 0
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2442)
at java.lang.Class.getMethod0(Class.java:2685)
at java.lang.Class.getMethod(Class.java:1620)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
Exception in thread "main" Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
I am able to run this code in eclipse.
VerifyError can mean the bytecode is invalid.
Basically, this is a compiler bug, or if class file is corrupted
Try compiling with a different JDK version and on a different machine.
I have created my menu with do~while(true); but every time the user insert a number, instead of running the program it shows the the menu again! what do you think?
// my main method
public static void main(String[] args) {
DataReader reader = new DataReader(); // The reader is used to read data from a file
// Load data from the file
if(reader.loadData(args[0])) { // The filename is entered using a command-line argument
vehicles= reader.getVehicleData(); // Store the arrays of Vehicle
// Display how many shapes were read from the file
System.out.println("Successfully loaded " + vehicles[0].getCount() +
" vehicles from the selected data file!");
displayMenu();
}
}
// dispaly menu method
private static void displayMenu() {
Scanner input = new Scanner(System.in);
do {
System.out.println("\n\n Car Sales Menu");
System.out.println("--------------------------------------");
System.out.println("1 - Sort vehicles by owner's Last Name");
System.out.println("2 - Sort vehicles by vehicle Model");
System.out.println("3 - Sort vehicles by vehicle Cost\n");
System.out.println("4 - List All Vehicles");
System.out.println("5 - List All Cars");
System.out.println("6 - List American Cars Only (Formal)");
System.out.println("7 - List Foreign Cars only (Formal)");
System.out.println("8 - List All Trucks");
System.out.println("9 - List All Bicycles");
System.out.print("\nSelect a Menu Option: ");
getInput(input.next()); // Get user input from the keyboard
}
while(true); // Display the menu until the user closes the program
}
// getInput method
private static void getInput(String input) {
switch(Convert.toInteger(input)) {
case 1: // Sort Vehicles by Owner's Last Name
Array.sortByOwnerName(vehicles);
break;
case 2: // Sort Vehicles by Vehicle Make & Model
Array.sortByVehicleMakeModel(vehicles);
break;
case 3: // Sort Vehicles by Vehicle Cost
Array.sortByVehicleCost(vehicles);
break;
case 4: // List All Vehicles
displayVehicleData(0);
break;
default:
System.out.print("The entered value is unrecognized!");
break;
}
}
Because you have while(true);, this means that the menu it will be in a infinite loop until a break is call.
Try to do something like:
do {
System.out.println("\n\n Car Sales Menu");
System.out.println("--------------------------------------");
System.out.println("1 - Sort vehicles by owner's Last Name");
System.out.println("2 - Sort vehicles by vehicle Model");
System.out.println("3 - Sort vehicles by vehicle Cost\n");
System.out.println("4 - List All Vehicles");
System.out.println("5 - List All Cars");
System.out.println("6 - List American Cars Only (Formal)");
System.out.println("7 - List Foreign Cars only (Formal)");
System.out.println("8 - List All Trucks");
System.out.println("9 - List All Bicycles");
System.out.print("\nSelect a Menu Option: ");
try {
int input = Integer.parseInt(getInput(input.next())); // Get user input from the keyboard
switch (input) {
case 1: // do something
break;
case 2: // do something
break;
...
}
} catch (NumberFormatException e) { ... }
}
while(true); // Display the menu until the user closes the program
You can use switch to process the input, and depending on input do the respective action.
while(true); // Display the menu until the user closes the program
while true doesn't mean exactly the thing that you have written in comment. You need to add some other condition in your while loop to check that condition. That condition should be on the input you read from the user.
For e.g, something like this. Note that this might not completely solve your problem, as there seems to be some other issues also with your code: -
int userInput = 0;
do {
try {
userInput = Integer.parseInt(getInput(input.next()));
} catch (NumberFormatException e) {
userInput = 0;
}
} while (userInput < 1 || userInput > 9);
return userInput; // For this you need to change return type of `displayMenu()`
And then, process the userInput returned in your main() method. There you would need to store the return value in some local variable.
int userInput = displayMenu();
Because your while loop is while(true) it will always keep looping until the program is forcefully broken. Without the content of your getInput() function, all that can be said is that the loop will never end.
You will need to handle your user's input, either in the getInput() method or after using it, and then conditionally break out of the while(true) when certain criteria are met.
Assuming your getInput method does what it says it does, you haven't actually done anything with your input once it has been read in.
So when the user enters a value, your program reads the value, happily ignores it, and then runs the menu again.