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.
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 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'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;
}
}
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;
}
}
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.