Beginners Java (Loops) - Vending machine - java

import java.util.Scanner;
public class cat{
public static void main(String args[]){
System.out.print("Enter a command = ");
double balance = 0;
String a;
//scanner input
Scanner in = new Scanner(System.in);
String command = in.nextLine();
while (in.hasNext()){
if (command.equals("penny")){
balance = balance + 0.01;
System.out.println("balance = " + balance);
}
if (command.equals("nickel")){
balance = balance + 0.05;
System.out.println("balance = " + balance);
}
else {
System.out.println("return" + balance + "to customer");
break;
}
balance++;
}
}
}
I'm trying to create an infinite loop that keeps reading new commands for a vending machine , that may halt only under certain condition - when the input is "return", it prints the current balance in the string "return $XX to customer". (otherwise it keeps adding/subtracting cash to the current balance).
First, I cannot seem to get the if and else part integrated together since both the string commands ("return ~ to customer "& "balance =") appears when I write 'penny'.
Second problem is that my intended infinite command loops just becomes a flow of infinite numbers in my terminal and I can't seem to figure out why.

Don'y know if it's what you're searching to do, but this loops unitil you send the break command:
import java.util.Scanner;
public class cat {
public static void main(String args[]) {
System.out.print("Enter a command = ");
double balance = 0;
String a;
// scanner input
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String command = in.nextLine();
if (command.equals("penny")) {
balance = balance + 0.01;
System.out.println("balance = " + balance);
} else if (command.equals("nickel")) {
balance = balance + 0.05;
System.out.println("balance = " + balance);
} else if (command.equals("break")) {
break;
} else {
System.out.println("return " + balance + " to customer");
}
balance++;
}
}
}

To fix your broken 'if' add yet another else:
else if (command.equals("nickel")){
With java7 you can use switch:
switch(command) {
case "nickel":
....
break;
case "penny":
.....
break;
default:
.....;
}

Related

How to store and modify balance on account:

I have a small acount in which to deposit, withdrawl, view balance, and exit. Everything runs perfectly however I would like the balance to ajust according to what method I do (withdrawal, deposit, etc.) I started with joptionpane but had the same problem and thought I should just start over. Anyone point me in the right direction?
Main file:
import java.util.Scanner;
public class Bank1
{
public static void main(String[] args)
{
HomeBank obj1 = new HomeBank();
Scanner keyboard = new Scanner(System.in);
String option;
char object;
System.out.println("This is your home banking account" + "\n");
do
{
System.out.println("What would you like to do today?"+ "\n" +
"\nSelect the following: " +
"\n'B' To View Balance." +
"\n'D' To Deposit" +
"\n'W' To Withdrawal" +
"\n'E' To Exit");
System.out.print("Your selection: ");
option = keyboard.next().toUpperCase();
object = option.charAt(0);
System.out.print("\n");
System.out.println("you entered: " +object+ "\n");
if(object =='D')
obj1.deposit();
else if(object =='W')
obj1.withdrawal();
else if(object =='B')
obj1.balance();
else
System.out.println("**Invalid input**" +
"\n Please try again");
} while(object !='E');
System.out.println("The End");
}
}
Class:
import java.util.InputMismatchException;
import java.util.Scanner;
public class HomeBank
{
private double withdrawal, deposit, balance;
public HomeBank()
{
balance = 100;
withdrawal = 50;
deposit = 150;
}
public HomeBank(double bal, double with, double de)
{
balance = bal;
withdrawal = with;
deposit = de;
}
public static void balance()
{
double balance = 250.00d;
System.out.println("You have $" + balance+"dollars");
}
public static void deposit()
{
Scanner keyboard = new Scanner(System.in);
double deposit = 0.00d;
double balance = 250.00d;
boolean goodput =true;
do
{
try
{
System.out.print("How much would you like to deposit today? :");
deposit = keyboard.nextDouble();
if(deposit > 0.00)
{
System.out.println("you entered $" +deposit+" dollars");
System.out.println("you now have $" + (deposit + balance)+" dollars");
goodput = false;
}
else
{
System.out.println("\n**Error**\nYou cannot deposit a "
+ "negative amount\n");
System.out.println("Please try again\n");
goodput = true;
}
}
catch (InputMismatchException x)
{
System.out.println("I'm sorry but that is an invalid input" +
"\nYou will be redirected to the main menu shortly..."+
"\n");
goodput = false;
}
} while (goodput == true);
}
public static void withdrawal()
{
Scanner keyboard = new Scanner(System.in);
double withdrawal = 0.00d;
double balance = 250.00d;
boolean goodput = true;
do
{
try
{
System.out.println("How much would you like to withdrawal?");
withdrawal = keyboard.nextDouble();
if (withdrawal < 0 || withdrawal > balance)
{
System.out.println("You have either entered a negative number"
+ "or trying to withdrawal more than is in your account");
System.out.println("You cannot withdrawal more than $"+balance);
System.out.println("Please try again");
goodput = true;
}
else
{
System.out.println("You now have $" +(balance-withdrawal)+ "dollars");
System.out.println("Thank you for choosing HomeBank\n"
+ "\nYou will be redirected to the main menu\n");
goodput =false;
}
}
catch (InputMismatchException x)
{
System.out.println("I'm sorry but that is an invalid input" +
"\nYou will be redirected to the main menu shortly..."+
"\n");
goodput = false;
}
} while (goodput == true);
}
}
The issue is how you are updating the values. In your methods, you have something that goes like the following:
double deposit = 0.00d;
double balance = 250.00d;
In there, notice how you are putting the double keyword before the variable. By doing that, you are telling Java to create a new variable named deposit and balance in the local scope.
If you want to modify the fields named deposit and balance, you would definitely have to remove the double keyword before them, and optionally put this. in front of the variable. It would look something like the following:
deposit = 0.00d;
balance = 250.00d;
Or
this.deposit = 0.00d;
this.balance = 250.00d;
You would replace all instances of the variables withdraw, balance, and deposit like that, but only the declaration.
The reason you don't need to specify the type is because you already define it in the field declaration. Therefore when you again define it in the method, you are saying to create a new variable with that name and type in the current scope.
Edit:
As Suyash Limaye said, you will have to remove the static keywords from the methods. Having the static keywords prevents the methods from being able to access the non-static fields, which will cause conflicts.

While loop not working accordingly

The following code asks the user to input the description, price and quantity of item he consumed.
There is a while loop to ask if he wants to input more items! If he does, the program ask to insert another description, price and quantity of the other items, and so on.
If he doesn't want to input more items, the output is all the items he added to the array, and the total of the bill.
Problem is: the first time the while runs, it works, but on the second time if the user answer with "y", it returns an error, as if he jumped from the description right to the price of the second item. If the user type the description, then it gets an input mismatch exception.
Main Class:
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Gastos> billArr = new ArrayList<>();
Scanner input = new Scanner(System.in);
int qntItems = 0 , counter = 0;
String ans;
Gastos bill = new Gastos();
while (qntItems == 0) {
System.out.print("Want to input another item? Y/N: ");
ans = input.nextLine();
switch (ans){
case "y":
qntItems = 0;
bill.setDescription();
bill.setPrice();
bill.setQuantity();
bill.getTotal();
billArr.add(bill);
counter = counter + 1;
break;
case "n": qntItems = 1;
break;
default: System.out.print("Invalid!");
System.out.println();
break;
}
input.close();
}
for (int i = 0; i < billArr.size();i++){
System.out.print(bill.getDescription() + ", " + bill.getPrice() + ", " + bill.getQuantity() + ", " + "the total is: " + bill.getTotal());
}
}
}
and the Gastos class:
package com.company;
import java.util.Scanner;
public class Gastos {
private String description;
private double price, quantity, total;
private Scanner input = new Scanner(System.in);
public void setDescription(){
System.out.print("Insert the item name: ");
description = input.nextLine();
}
public void setPrice(){
System.out.print("insert the item price: ");
price = input.nextDouble();
}
public void setQuantity(){
System.out.print("Insert the quantity: ");
quantity = input.nextDouble();
}
public String getDescription(){
return description;
}
public double getPrice() {
return price;
}
public double getQuantity() {
return quantity;
}
public double getTotal(){
total = price * quantity;
return total;
}
}
How can I handle this error?
You have a bug in your 2nd loop.
It should be:
System.out.print(billArr.get(i).getDescription().....
or simply put:
for(Gastos b : billArr){
System.out.print(b.getDescription())
}
Update 1: Another error is you close the Scanner at the end of the first loop. Move input.close(); outside the loop or inside case "n".
Update 2: You have another problem, you need to reinitialize Gastos every time you enter new details about it. So you need to do Gastos bill = new Gastos(); right after case "y": and remove it from where you initialize it before the while loop. Your main should look like this:
public static void main(String[] args) {
ArrayList<Gastos> billArr = new ArrayList<>();
Scanner input = new Scanner(System.in);
int qntItems = 0 , counter = 0;
String ans;
while (qntItems == 0) {
System.out.print("Want to input another item? Y/N: ");
ans = input.nextLine();
switch (ans){
case "y":
Gastos bill = new Gastos();
qntItems = 0;
bill.setDescription();
bill.setPrice();
bill.setQuantity();
bill.getTotal();
billArr.add(bill);
counter = counter + 1;
break;
case "n": qntItems = 1;
input.close();
break;
default: System.out.print("Invalid!");
System.out.println();
break;
}
}
for (Gastos bill : billArr){
System.out.print(bill.getDescription() + ", " + bill.getPrice() + ", " + bill.getQuantity() + ", " + "the total is: " + bill.getTotal());
}
}
I think you need to spend sometime debugging and understanding how java's objects work. These are basic errors which should be easily caught.

Java -if else displays multiple outputs

I have this bit of code to return to the beginning of the program if an answer is not expected.
...
else // returns to start for unsatisfactory
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
}
...
however when I enter a different word then go through again and enter an expected word the program outputs two different results
Current Salary: $100.00
Amount of your raise: $4.00
Your new salary: $104.00
Current Salary: $100.00
Amount of your raise: $0.00
Your new salary: $100.00
I tried using an else if statement to possibly eliminate that as a cause but it caused the same thing.
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary {
public static void main (String[] args) {
double currentSalary; // employee's current salary
double raise = 0.0; // amount of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
// Computes raise with if-else
if ((rating.equals("Excellent")) || (rating.equals("excellent"))) {
// calculates raise for excellent
raise = .06 * currentSalary;
}
else if ((rating.equals("Good")) || (rating.equals("good"))) {
// calculates raise for good
raise = .04 * currentSalary;
}
else if ((rating.equals("Poor")) || (rating.equals("poor"))) {
// calculates raise for poor
raise = .015 * currentSalary;
}
else {
// returns to start for unsatisfactory
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
}
newSalary = currentSalary + raise;
// Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
That is because you call main recursively (which is not considered good practice BTW) when you don't get an expected input. After you enter (the 2nd time) an expected input, the remainder of the initial main must still be executed which will then work with a raise of 0.0 as the input was invalid.
A pragmatic solution for your issue could be avoiding the recursive call to main and wrap e.g. the input validation in a loop like so
...
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
while (true) {
rating = scan.next();
if ((rating.equals("Excellent")) || (rating.equals("excellent")))
{
raise = .06 * currentSalary; break;
}
else if ((rating.equals("Good")) || (rating.equals("good")))
{
raise = .04 * currentSalary; break;
}
else if ((rating.equals("Poor")) || (rating.equals("poor")))
{
raise = .015 * currentSalary; break;
}
else
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
}
}
...
You're not returning after you call main (args); so every iteration of your program will continue.
You should add return; after main (args);
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
return;
}
edit: as pointed out by John3136 you shouldn't be calling main (args) recursively either.
That (second) call you make to main() "finishes" and comes back out to the "first" one that was invoked by starting the program.
So the first lot of results are from your explicit call to main(). The second lot is from when that call ends and you are back to where you called from.
Calling main() recursively is not recommended. You should use a while loop inside main(). i.e. Keep asking for input until you know the input is valid, and then actually use it.
You should not call main recursively.you should use do while loop as I update code and it's working fine.
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary {
public static void main (String[] args) {
double currentSalary; // employee's current salary
double raise = 0.0; // amount of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
boolean flag=false; // to check input
Scanner scan = new Scanner(System.in);
do{
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
// Computes raise with if-else
if ((rating.equals("Excellent")) || (rating.equals("excellent"))) // calculates raise for excellent
{
raise = .06 * currentSalary;
flag=true;
}
else if ((rating.equals("Good")) || (rating.equals("good"))) // calculates raise for good
{
raise = .04 * currentSalary;
flag=true;
}
else if ((rating.equals("Poor")) || (rating.equals("poor"))) // calculates raise for poor
{
raise = .015 * currentSalary;
flag=true;
}
else // returns to start for unsatisfactory
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
flag=false;
}
}while(!flag);
newSalary = currentSalary + raise;
// Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
You may want to consider another approach. Either terminate the problem in case the input is invalid or try to repair it. The following example is for the "repair" approach,
public class Salary {
public static void main(String[] args) {
IPM ipm;
if (verify(args)) {
ipm = new IPM(args);
} else {
Scanner scan = new Scanner(System.in);
String[] update;
do {
update = repair(scan);
} while (!verify(update)); // You may want a loop count as well...
ipm = new IPM(update);
}
ipm.print();
}
public static boolean verify(String[] s) {
return IPM.verify(s);
}
public static String[] repair (Scanner s) {
// Request new input and store it in an array of strings.
// This method does not validate the input.
}
}
public class IPM {
double currentSalary;
double raise = 0.0;
double newSalary;
String rating;
IPM(String[] input) {
// Set attributes of IPM.
}
public static boolean verify(String[] s) {
//Determine if the input is valid.
}
public void print() {
// Print IPM object.
}
}
Note that the call to IPM.verify() from salary. This should be a part of the responsibility of IPM since Salary is not require to know anything about main. Also, the class IPM might change and a call to IPM.verify() will not require that all classes which verifies the IPM are changed as well.

Odd error in my Java program

I have a Java program that is designed to take an input of customers, then run a loop for each. Then the user has 3 choices to input: clowns, safari sam, or music caravan. I just don't understand what is wrong with my if statements. You see, if a user enters "clowns", the corresponding if statement works fine and the if statement is executed. However, if a user inputs "safari sam" or "music caravan", the if statements do not execute.
My question is: If the first if statement is executed, then why are the other 2 being skipped (not executing when conditions are met)?
CODE:
import java.util.Scanner;
public class FunRentals {
public static void main(String[] args) {
Scanner new_scan = new Scanner(System.in);
System.out.println("Enter the amount of customers: ");
int num_customers = new_scan.nextInt();
for(int i = 1; i<=num_customers; i++){
System.out.println("Please enter the service used (\"Clowns\", \"Safari Sam\", or \"Music Caravan\") for customer #"+i);
String service_type = new_scan.next();
String service_type_real = service_type.toLowerCase();
if(service_type_real.equals("clowns")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ clowns(additional_hours));
}
else if(service_type_real.equals("safari sam")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ safari_sam(additional_hours));
}
else if(service_type_real.equals("music caravan")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ music_caravan(additional_hours));
}
}
}
public static double clowns(double a){
double additional_cost = a*35;
double total_cost = additional_cost + 45;
return total_cost;
}
public static double safari_sam(double a){
double additional_cost = a*45;
double total_cost = additional_cost + 55;
return total_cost;
}
public static double music_caravan(double a){
double additional_cost = a*30;
double total_cost = additional_cost + 40;
return total_cost;
}
}
You need to use nextLine() instead of next() to read user input. nextLine() will read the entire line, but next() will only read the next word.
For reading String provided by the user in console you have to use .nextLine()
So try by using this -
String service_type = new_scan.nextLine();
This should store the value of whatever you are providing in the console to the String "service_type".

How do I terminate the program in Java?

This is my code. The program won't give me the last print line "Thank you for using the Basic user Interface program."
public class nameClass {
public static void main(String[] args) {
String input;
String name;
int age;
double mileage;
displayApplicationInformation();
displayDivider("Start Program");
TerminateApplication();
// process name
displayDivider("Get Name");
name = getInput("name");
System.out.println("Your name is: " + name);
// Process age
displayDivider("Get Age");
input = getInput("Your age");
age = Integer.parseInt(input);
System.out.println("Your age is: " + age);
// Process Mileage
displayDivider("Get Mileage");
input = getInput("Your MPG");
mileage = Double.parseDouble(input);
System.out.println("Your car MPG is: " + mileage);
}// end of main
public static void displayApplicationInformation()
{
System.out.println("Welcome to the Basic User Interface Program");
}// end of displayApplicaionInformation
public static void displayDivider(String outputTitle) {
System.out.println("*********" + outputTitle + "********");
}// end of displayDvider
public static String getInput(String inputType)
{
String input = "";
input = JOptionPane.showInputDialog("Enter the " + inputType);
return input;
}
public static void TerminateApplication()
{
System.out.println("Thank you for using the Basic User Interface program");
return;
}
}// end of MainClass
You have to actually call the method TerminateApplication;
System.out.println("Your car MPG is: " + mileage);
TerminateApplication();
Simple, call TerminateApplication.
You are doing it on the 9th line of main().
Here, check this out:
displayDivider("Get Mileage");
input = getInput("Your MPG");
mileage = Double.parseDouble(input);
System.out.println("Your car MPG is: " + mileage);
//add this...
TerminateApplication();
Hope this helps!

Categories

Resources