Betty Jones
Betty Jones

Reputation: 73

Beginners Java (Loops) - Vending machine

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.

Upvotes: 0

Views: 1809

Answers (2)

Andrea Colleoni
Andrea Colleoni

Reputation: 6021

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++;
    }

 }
}

Upvotes: 1

kofemann
kofemann

Reputation: 4423

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

Upvotes: 0

Related Questions