i'm getting an infinite loop with the program i'm doing and i'm not sure how to get passed it. been working at this a few hours and i cant figure it out. (sorry if this seems very simple to you guys, but i'm still new at java). basically what is happening is that everything compiles and works as it should at first, but as soon as i enter a selection it repeats the main menu WITHOUT giving me the intended operation.
for example, the program should work to where i enter "1, 2, 3, or 4" as a selection and it displays "Good morning" in English, Italian, Spanish, and German respectively and 5 ends the program. what happens instead is that the menu repeats itself if i enter 1, 2, 3, 4, or 5 as a selection.
entering any number other than 1-5 displays an error message saying that the selection is invalid, as it should. so that while loop works as intended. so can anyone point out what i did wrong?
import java.util.Scanner;
import java.io.*;
public class Translator
{
public static void main(String[] args)
{
// local variable to hold the menu selection
int selection = 0;
do
{
// display the menu
displayMenu(selection);
// perform the selected operation
switch (selection)
{
case 1:
System.out.println("Good Morning.");
break;
case 2:
System.out.println("Buongiorno.");
break;
case 3:
System.out.println("Buenos dias.");
break;
case 4:
System.out.println("Guten morgen.");
break;
case 5:
System.out.println("GoodBye!");
break;
}
} while (selection != 5);
}
// the displayMenu module displays the menu and gets and validates
// the users selection.
public static void displayMenu(int selection)
{
//keyboard scanner
Scanner keyboard = new Scanner(System.in);
// display the menu
System.out.println(" select a language and i will say good morning");
System.out.println("1. English.");
System.out.println("2. Italian.");
System.out.println("3. Spanish.");
System.out.println("4. German.");
System.out.println("5. End the Program.");
System.out.println("Enter your selection");
// users selection
selection = keyboard.nextInt();
while (selection < 1 || selection > 5)
{
System.out.println ("that is an invalid select.");
System.out.println (" Enter 1, 2, 3, 4, or 5.");
selection = keyboard.nextInt();
}
}
}
The problem is that arguments to methods are passed by value in Java. So the part at the end of displayMenu where you set a new value for the selection parameter doesn't change the value of the selection local variable in main at all. So in main, the selection variable always has the value of 0.
Given that you're not using the original value of selection in displayMenu, you should just turn it into a method with no parameters, but which returns the selected value:
public static int displayMenu()
{
// Code to print out the menu [...]
int selection = keyboard.nextInt();
while (selection < 1 || selection > 5)
{
System.out.println ("that is an invalid select.");
System.out.println (" Enter 1, 2, 3, 4, or 5.");
selection = keyboard.nextInt();
}
return selection;
}
And in main:
int selection;
do
{
selection = displayMenu();
switch (selection)
{
...
}
}
while (selection != 5);
Java doesn't support "true" pass-by-reference, which is what your program seems to rely on. You initialize a variable to 0 and ask a method to change it, which can't happen. The parameter values you have inside methods are mere copies of the original values passed to them. A small demonstration: consider you have this method...
public static void increment(int a) {
a++;
}
and a code that uses it...
int a = 0;
increment(a);
System.out.println(a);
0 is printed, because the only thing that's incremented is the local copy of a in the method increment. The original value stays unchanged.
You could make your method instead return a value as suggested in Jon Skeet's answer.
the simplest solution when you stuck in a program is that use debug tools.
begug tools that exist in every compiler like eclipse or netbeans not only in this program but also in any program can help you.
then come back to your project and use this tools. you can find your wrong.
good luck!!
You call displayMenu() within the do-while loop and there is a problem with passing values between methods. And yes there is problem with your indentation. Check topics like control statements, variables in a book. An improved version is shown below:
package imporvedtranslator;
import java.io.*;
import java.util.Scanner;
public class ImporvedTranslator
{
public static void main(String[] args)
{
int selection;
selection = displayMenu();
switch (selection)
{
case 1:
System.out.println("Good Morning.");
break;
case 2:
System.out.println("Buongiorno.");
break;
case 3:
System.out.println("Buenos dias.");
break;
case 4:
System.out.println("Guten morgen.");
break;
case 5:
System.out.println("GoodBye!");
break;
}
}
private static int displayMenu()
{
int sel;
Scanner sc = new Scanner(System.in);
System.out.println(" select a language and i will say good morning");
System.out.println("1. English.");
System.out.println("2. Italian.");
System.out.println("3. Spanish.");
System.out.println("4. German.");
System.out.println("5. End the Program.");
System.out.println("Enter your selection");
sel = sc.nextInt();
while (sel<1 || sel>5)
{
System.out.println ("that is an invalid select.");
System.out.println (" Enter 1, 2, 3, 4, or 5.");
sel = sc.nextInt();
}
return sel;
}
}
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 new to programming so I'm not able to complete this programme.
I'm required to create a fast food eatery that asks the customer's name, their choice, quantity, phone number, and whether they would like to order something else.
I'm managed to take the inputs from the customer but the only problem is that I can't I can't figure out to add the subtotal if the customers chooses to order something else. Like if they had the total of $10 and make an order of another $10, how am I supposed to add the total and display the bill?
I apologize if I'm not able to explain myself.
Here's what I've done till now:
import java.util.*;
public class KFC
{
public void display_menu()
{
System.out.println("**********WELCOME TO XYZ**********");
System.out.println("MAY I KNOW WHAT WOULD YOU LIKE?");
System.out.println("1.OMG Burger:-");
System.out.println("2.OMG Roller:-");
System.out.println("3.Chicken Snacker:-");
System.out.println("Please enter your choice");
}
public void question()
{
System.out.println("Would you like to have something else?");
System.out.println("To place another order enter 9.");
System.out.println("To check out enter 0.");
Scanner q = new Scanner(System.in);
switch (q.nextInt())
{
case 0:
break;
case 9:System.out.println ("Please proceed.");
new KFC();
break;
default:System.out.println ( " option" );
break;
}
}
public KFC()
{
Scanner sc = new Scanner(System.in);
display_menu();
switch (sc.nextInt())
{
case 1:int a,b,Rate;String s;
double e,t,f,g;
float m;
System.out.println("OMG Burger");
System.out.println("Enter The Quantity");
b=sc.nextInt();
System.out.println("Enter Your Name");
s=sc.next();
System.out.println("Enter Your Mobile Number");
m=sc.nextFloat();
Rate=49;
t=(5.0/100.0)*Rate;
e=b*Rate;
f=t*b;
g=e+f;
question();
System.out.println("***********KFC**********");
System.out.println("Name:"+s);
System.out.println("Mobile Number:"+m);
System.out.println("Choice:OMG Burger");
System.out.println("Quantity:"+b);
System.out.println("Rate:$"+Rate);
System.out.println("Tax:"+f);
System.out.println("Total price:$"+g);
System.out.println("PLEASE VISIT AGAIN. HAVE A NICE DAY!!!");
break;
case 2: System.out.println("OMG Roller");
System.out.println("Enter The Quantity");
b=sc.nextInt();
System.out.println("Enter Your Name");
s=sc.next();
System.out.println("Enter Your Mobile Number");
m=sc.nextFloat();
Rate=59;
t=(5.0/100.0)*Rate;
e=b*Rate;
f=t*b;
g=e+f;
question();
System.out.println("***********KFC**********");
System.out.println("Name:"+s);
System.out.println("Mobile Number:"+m);
System.out.println("Choice:OMG Roller");
System.out.println("Quantity:"+b);
System.out.println("Rate:$"+Rate);
System.out.println("Tax:"+f);
System.out.println("Total price:$"+g);
System.out.println("PLEASE VISIT AGAIN. HAVE A NICE DAY!!!");
break;
case 3: System.out.println("Chicken Snacker");
System.out.println("Enter The Quantity");
b=sc.nextInt();
System.out.println("Enter Your Name");
s=sc.next();
System.out.println("Enter Your Mobile Number");
m=sc.nextFloat();
Rate=40;
t=(5.0/100.0)*Rate;
e=b*Rate;
f=t*b;
g=e+f;
question();
System.out.println("***********KFC**********");
System.out.println("Name:"+s);
System.out.println("Mobile Number:"+m);
System.out.println("Choice:Chicken Snacker");
System.out.println("Quantity:"+b);
System.out.println("Rate:$"+Rate);
System.out.println("Tax:"+f);
System.out.println("Total price:$"+g);
System.out.println("PLEASE VISIT AGAIN. HAVE A NICE DAY!!!");
break;
default:
System.out.println ( "Unrecognized option" );
break;
}
}
public static void main (String[]args)
{
new KFC();
}
}
Initially you are creating new instance of KFC for the a new customer....now when same customer place another order again you create new instance of KFC rather using same instance..bcoz you have placed your logic inside constructor which is totally wrong. As pointed out by oguzhand this will not help in totalling
Constructors are used to initialize the instances of your classes. Often it is used to create new objects often with parameters specifying the initial state or other important information about the object
From the official Java tutorial:
A class contains constructors that are invoked to create objects from
the class blueprint.
For more info on constructors refer
1)So instead of writing your logic inside constructor....write it in a method and call that method.
2)Also as pointed out by RC and oguzhand you should give meaningful names to variable and should use few global variable. For Example
String customerName;
long customerContactNo;
long totalPrice;
int burgerQuantity;
int rollerQuantity;
Points already made by others:
1) Name your variables using some meaningful name
2) Don't do your work in the constructor
It seems as though you're trying to write a program to solve your problem rather than to write a set of classes. When working in Java, you ought to be creating an object oriented solution to the problem.
Ask yourself first about how many of something you have. For each order, how many customers? How many menu items in an order? Since a single customer can order more than one menu item, you should have a class for menu items ordered in a single order.
So far I'm seeing at least three different classes to be written:
1) A class to represent a working day at your restaurant;
2) A class to represent an order; and
3) A class to represent an item in the order.
To get the subtotal for the order, you can just iterate over the OrderItem objects, ask each one how much it costs, and add that to a variable. Store the value in a field on the Order class (or recalculate and return it whenever it's needed) and you're good to go.
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.
The method bankTellerMenu() is intended to show a bank teller menu and repeatedly obtain the user’s selection and execute that selection. The menu is only redisplayed if an invalid choice is made by the user. There are syntax and logical errors in the method. If these errors were corrected then the actual output would match that displayed below.
Correct the code and test it by producing the output below. I have underlined user responses to make them stand out.
------------------------- Expected output --------------------------
FIT Bank
Deposit
Withdraw
Client Menu
Account Menu
Exit
Select an option (1-5): 7
FIT Bank
Deposit
Withdraw
Client Menu
Account Menu
Exit
Option must be only 1-5
Select an option (1-5): 2
* Invoke withdraw()
Select another option (1-5): 5
------------------------- Expected output --------------------------
Now the problem starts now, i have tried out coding the method, but it doesn't seem to be able to invoke withdraw() or any other choices when i input a value that is between 1 and 5. Can someone help please?
import java.util.*;
public class FITBank
{
//There are no errors in the main method.
public static void main(String[] args)
{
//Just run bank teller menu.
bankTellerMenu();
}
public static void bankTellerMenu()
{
Scanner reader = new Scanner(System.in);
int option = 1;
String message = null;
do{
System.out.println("\n\tFIT Bank");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Client Menu");
System.out.println("4. Account Menu");
System.out.println("5. Exit");
if(message!=null){
System.out.println("\t"+message);
}
System.out.print("Select an option (1-5): ");
option = reader.nextInt();
if(option < 1 || option > 5){
message = new String("Option must be only 1-5");
option=1;
}
}while(option <1 && option > 5);
if(option == 1) {
System.out.println("***\tInvoke deposit()");
}
if(option == 2){
System.out.println("***\tInvoke withdraw()");
}
if(option == 3)
{ System.out.println("***\tInvoke clientMenu()");
}
if(option==4){
System.out.println("***\tInvoke accountMenu()");
}
}
}
First and foremost: are you familiar with the switch statement? If you're not, then I think this would be a perfect time to learn about it.
Now the problem starts now, i have tried out coding the method, but it doesn't seem to be able to invoke withdraw() or any other choices when i input a value that is between 1 and 5.
Without doing your homework: if you want to invoke the withdraw method, you must have a withdraw method to invoke. So where is your withdraw method? Or are you just supposed to print that you're calling the withdraw method without actually calling it?
You are closing your loop to early. Move all the if(option == ...) statements right before
}while(option >=1 && option < 5);. Otherwise this won't work as expected.
Also I would recommend using a switch statement instead of all those if statements.