I wrote this java program that performs functions of a vending mention. But now I need to write it using methods, how can I do this? Here is my code: (Any help would be greatly appreciated!

import java.util.Scanner;
import java.util.Random;

public class VendingMachine
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in); // reader for standard input
Random random = new Random(); // random number generator
int[] items = {65, 95, 50, 110, 75}; // prices for five items in cents
int[] coins = {5, 10, 25, 100}; // nickel, dime, quarter and dollar
boolean exactChange; // whether exact change is required flag
int price; // price of item
int amount; // amount deposited
boolean cancelSelection; // flag to indicate if selection is cancelled
int sales; // total number of sales
int remaining;
int count;
int choice;
int select;
char ch;

exactChange = random.nextBoolean();
sales = 0;
choice = 1;

do
{
if (sales == 10)
{
System.out.println("OUT-OF-SERVICE…
System.out.print("Do you want to make the machine operational? (y/n): ");
ch = keyboard.next().toUpperCase().charAt(0);
if (ch == 'Y')
sales = 0;
}
else
{
System.out.println("--------------");
System.out.println(" Vending Machine ");
System.out.println("--------------");
for (int i=0; i<items.length; i++)
System.out.println((i+1) + ". Item price " + items[i] + " cents");

System.out.println((items.length + 1) + ". Exit");
System.out.println("Exact change to be inserted: " + exactChange);
System.out.print("Enter the choice: ");
choice = keyboard.nextInt();

if (choice >= 1 && choice <= items.length)
{
price = items[choice-1];
amount = 0;
cancelSelection = false;

while (amount < price)
{
System.out.println("-----------");
System.out.println(" Deposit Money ");
System.out.println("-----------");
System.out.println("1. Nickel");
System.out.println("2. Dime");
System.out.println("3. Quarter");
System.out.println("4. Dollar");
System.out.println("5. Cancel selection");
System.out.print("Enter the amount: ");
select = keyboard.nextInt();

if (select >= 1 && select <= 4)
{
amount = amount + coins[select-1];
}
else if (select == 5)
{
cancelSelection = true;
break;
}
else
{
System.out.println("Error: you have entered an invalid selection, try again");
}
}

if (!cancelSelection)
{
if (!exactChange)
{
if (amount == price)
{
System.out.println("No change due");
}
else
{
System.out.println("Changes are:");
remaining = amount - price;

// get the number of one dollars
count = remaining / 100;
if (count == 1)
System.out.println("1 dollar");
else if (count > 1)
System.out.println(count + " dollars");
remaining = remaining % 100;

// get the number of 25 cents
count = remaining / 25;
if (count == 1)
System.out.println("1 quarter");
else if (count > 1)
System.out.println(count + " quarters");
remaining = remaining % 25;

// get the number of 10 cents
count = remaining / 10;
if (count == 1)
System.out.println("1 dime");
else if (count > 1)
System.out.println(count + " dimes");
remaining = remaining % 10;

// get the number of 5 cents
count = remaining / 5;
if (count == 1)
System.out.println("1 nickel");
else if (count > 1)
System.out.println(count + " nickels");
}
}

exactChange = random.nextBoolean();
sales += 1;
}
}
else if (choice != (items.length + 1))
{
System.out.println("Error: you have entered invalid choice");
}
}
} while (choice != (items.length + 1));
}
}

So basically a method works like a machine that accepts some input and does something based on that input. Usually it is useful for organizing your code so you don't get a crazy-long main function like the one you ended up with. I shortened your main function using some methods, but I did it quickly -- you can probably perfect it by including more specialized methods. In general it is easier to begin by thinking of methods rather than writing it all in your main method and then trying to split it up afterward. Here is what I came up with. I made 3 methods -- 2 of them to display stuff so you don't have to use all those print functions clogging up your main, and one of them to display the change since you repeated that piece of code for all 4 coins. Basically if there is a piece of code you keep repeating that u are practically copy-pasting, it can better be accomplished by a method. There are some advanced coding techniques, such as Object-Oriented coding, that could have helped you out in this code in organization and readability, but I just used simple method decomposition so you would understand the changes. Compare my code to your code and see if you can follow it.

import java.util.Scanner;
import java.util.Random;

public class VendingMachine
{
    public static int calculateChange(int remaining, int coinValue, String coinName)
    {
        int count = remaining / coinValue;
        if (count == 1)
        System.out.println("1 "+coinName);
        else if (count > 1)
        System.out.println(count + " "+coinName+"s");
        return remaining % coinValue;
    }

    public static int deposit()
    {
        Scanner keyboard = new Scanner(System.in); // reader for standard input
        System.out.println("-----------");
        System.out.println(" Deposit Money ");
        System.out.println("-----------");
        System.out.println("1. Nickel");
        System.out.println("2. Dime");
        System.out.println("3. Quarter");
        System.out.println("4. Dollar");
        System.out.println("5. Cancel selection");
        System.out.print("Enter the amount: ");
        return keyboard.nextInt();
    }
    public static int displayMenu(int[] items, boolean exactChange)
    {
        Scanner keyboard = new Scanner(System.in); // reader for standard input
        System.out.println("--------------");
        System.out.println(" Vending Machine ");
        System.out.println("--------------");
        for (int i=0; i<items.length; i++)
            System.out.println((i+1) + ". Item price " + items[i] + " cents");
        
        System.out.println((items.length + 1) + ". Exit");
        System.out.println("Exact change to be inserted: " + exactChange);
        System.out.print("Enter the choice: ");
        return keyboard.nextInt();
    }
    
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in); // reader for standard input
        Random random = new Random(); // random number generator
        int[] items = {65, 95, 50, 110, 75}; // prices for five items in cents
        int[] coins = {5, 10, 25, 100}; // nickel, dime, quarter and dollar
        boolean exactChange; // whether exact change is required flag
        int price; // price of item
        int amount; // amount deposited
        boolean cancelSelection; // flag to indicate if selection is cancelled
        int sales; // total number of sales
        int remaining;
        int choice;
        int select;
        
        exactChange = random.nextBoolean();
        sales = 0;
        choice = 1;
        
        do
        {
            if (sales == 10)
            {
                System.out.println("OUT-OF-SERVICE…");
                System.out.print("Do you want to make the machine operational? (y/n): ");
                char ch = keyboard.next().toUpperCase().charAt(0);
                if (ch == 'Y')
                    sales = 0;
            }
            else
            {
                choice = displayMenu(items,exactChange);
            
                if (choice >= 1 && choice <= items.length)
                {
                    price = items[choice-1];
                    amount = 0;
                    cancelSelection = false;
            
                    while (amount < price)
                    {
                        select = deposit();
            
                        if (select >= 1 && select <= 4)
                        {
                            amount = amount + coins[select-1];
                        }
                        else if (select == 5)
                        {
                            cancelSelection = true;
                            break;
                        }
                        else
                        {
                            System.out.println("Error: you have entered an invalid selection, try again");
                        }
                    }
            
                    if (!cancelSelection)
                    {
                        if (!exactChange)
                        {
                            if (amount == price)
                            {
                                System.out.println("No change due");
                            }
                            else
                            {
                                System.out.println("Changes are:");
                                remaining = amount - price;
            
                                // get the number of one dollars
                                remaining = calculateChange(remaining,100,"dollar");
            
                                // get the number of 25 cents
                                remaining = calculateChange(remaining,100,"quarter");
            
                                // get the number of 10 cents
                                remaining = calculateChange(remaining,5,"dime");
            
                                // get the number of 5 cents
                                remaining = calculateChange(remaining,5,"nickel");
                            }
                        }
            
                        exactChange = random.nextBoolean();
                        sales += 1;
                    }
                }
                else if (choice != (items.length + 1))
                {
                    System.out.println("Error: you have entered invalid choice");
                }
            }
        }
        while (choice != (items.length + 1));
    }
}

@kvass next time provide hints not whole solution. It is better that person asking question try these suggestions and if is having problems can always come back ask for more advice. That is the way to learn programming language at the start, not copy & paste someone solution....

commented: Exactly :) +7

I would agree that hints normally are usually the best way to solve a problem that someone is struggling with, but in this case the code was all correct and habibalbi was just asking about reformatting the code. I don't think that providing hints for the methods really would have been clear -- the best way to learn about using methods is visually. I provided a rough sketch of what you could do with some methods, but I provided it in the context of the code. It's far from solved -- if I were habibalbi I would probably now use this idea and rewrite the code so the main method basically only contains method calls. Sometimes hints aren't adequate for comprehension of a concept. For instance, I had problems previously about threading and I needed some help -- if someone had just gave me a vague hint it wouldn't have been useful at all. However, I got a clear cut example -- a modification of my original code -- and thus I was able to better understand the concept.

This would be sufficient Defining Methods, Passing Information to a Method or a Constructor an example

/**
* This method will return deposit entered by user 
* return int representing amount of money
*/
public static int deposit()
{
//here comes to make deposit
//ask user to enter amount
}

/**
* This method provides user with start-up menu of vending machine
*@param items[]
*@param exactChange
* return int value representing selection made by user
*/
public static int displayMenu(int[] items, boolean exactChange)
{
// here comes code to display start-up menu
}

PS: Deposit method is wrong. Where do you record what sort of coin was inserted?

That part is done in the actual code where the while loop is -- I had the deposit method just do the printing -- evaluating the response is done where the deposit method is called.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.