Amazon Interview Question for Software Engineer / Developers


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
4
of 4 vote

Here is the Complete Code

VendingMachine.java

package statepattern;
import statepattern.exception.MachineWarning;
public class VendingMachine {
    State coninInsertedState = new CoinInsertedState(this);
    State emptyState = new EmptyState(this);
    State noCoinInsertedState = new NoCoinInsertedState(this);
    State dispensingState = new DispensingState(this);
    State machineState = null;
    int capacity = 0;
    public VendingMachine() {
        machineState = noCoinInsertedState;
    }
    public void reFill(int count) {
        capacity += count;
        machineState = noCoinInsertedState;
    }
    /**
     * Two Actions performed by MAchine   
     */
    public void insertCoin() throws MachineWarning {
        machineState.insertCoin();
    }
    
    public void pressButton() throws MachineWarning {
        machineState.pressButton();
        machineState.dispense();
        capacity--;
    }
    
    public boolean isEmpty(){
        if(capacity<=0)
            return true;
        else
            return false;
    }
    
    public void setMachineState(State machineState) {
        this.machineState = machineState;
    }
    public State getMachineState() {
        return machineState;
    }
    public void setConinInsertedState(State coninInsertedState) {
        this.coninInsertedState = coninInsertedState;
    }
    public State getConinInsertedState() {
        return coninInsertedState;
    }
    public void setEmptyState(State emptyState) {
        this.emptyState = emptyState;
    }
    public State getEmptyState() {
        return emptyState;
    }
    public void setNoCoinInsertedState(State noCoinInsertedState) {
        this.noCoinInsertedState = noCoinInsertedState;
    }
    public State getNoCoinInsertedState() {
        return noCoinInsertedState;
    }
    public void setDispensingState(State dispensingState) {
        this.dispensingState = dispensingState;
    }
    public State getDispensingState() {
        return dispensingState;
    }
    public void setCapacity(int capacity) {
        this.capacity = capacity;
    }
    public int getCapacity() {
        return capacity;
    }
}


State interface



import statepattern.exception.MachineWarning;
public interface State {
   
    public void insertCoin()throws MachineWarning;
    public void pressButton()throws MachineWarning;
    public void dispense()throws MachineWarning;
}


Concrete States implementations



ConinINsertedState.java



package statepattern;
import statepattern.exception.MachineWarning;
public class CoinInsertedState implements State{
    VendingMachine machine =null;
    public CoinInsertedState(VendingMachine machine) {
        this.machine =  machine;
    }
    public void insertCoin() throws MachineWarning{
        throw new MachineWarning("Coin is already inserted.");
    }
    public void dispense() throws MachineWarning{
        throw new MachineWarning("Dispense button is not pressed.");
    
    }
    public void pressButton() throws MachineWarning{
        machine.setMachineState(machine.getDispensingState());
    }
}


DispensingState.java



package statepattern;
import statepattern.exception.MachineWarning;
public class DispensingState implements State{
    VendingMachine machine ;
    DispensingState(VendingMachine machine) {
        this.machine = machine;
    }
    public void insertCoin() throws MachineWarning {
        throw new MachineWarning("wait ... previous order is processing");
    }
    public void pressButton() throws MachineWarning {
        throw new MachineWarning("wait ... previous order is processing");
    }
    public void dispense() throws MachineWarning {
        machine.setMachineState(machine.getNoCoinInsertedState());
    }
}


EmptyState.java



package statepattern;
import statepattern.exception.MachineWarning;
public class EmptyState implements State{
    VendingMachine machine;
    public EmptyState(VendingMachine machine) {
        this.machine =  machine;
    }
    public void insertCoin() throws MachineWarning{
        throw new MachineWarning("Can not process the request");
    }
    public void pressButton() throws MachineWarning{
        throw new MachineWarning("Invalid Action");
    }
    public void dispense() throws MachineWarning{
        throw new MachineWarning("Invalid Action");
    }
}


NoCoinInsertedState.java


package statepattern;
import statepattern.exception.MachineWarning;
public class NoCoinInsertedState implements State{
    VendingMachine machine;
    public NoCoinInsertedState(VendingMachine machine) {
        this.machine =  machine;
    }
    public void insertCoin() throws MachineWarning{
        if (!machine.isEmpty()) {
            machine.setMachineState(machine.getConinInsertedState());
        }
        else {
            throw new MachineWarning("Can not process request .. Machine is out of stock");
        }
    }
    public void pressButton() throws MachineWarning{
        throw new MachineWarning("No coin inserted ..");
    }
    public void dispense() throws MachineWarning{
        throw new MachineWarning("Invalid Operation");
    }
}


I have run the Test class to check behavior of Vending MAchine in different states 


Test.java


package statepattern.test;
import statepattern.exception.MachineWarning;
import statepattern.VendingMachine;
public class Test {
    public Test() {
    }
    public static void main(String[] args) {
        VendingMachine machine = new VendingMachine();
        machine.reFill(2); // 
        //First despense 
        try {
            machine.insertCoin();
            machine.pressButton();
        } catch (MachineWarning e) {
            System.out.println("Test 1:" + e.getMessage());
        }
        //Second Test 
        try {
            machine.insertCoin();
            machine.insertCoin();
            machine.pressButton();
        } catch (MachineWarning e) {
            System.out.println("Test 2:" + e.getMessage());
            try {
                machine.pressButton();
            } catch (MachineWarning f) {
                // TODO
            }
        }
        //Test THree 
        try {
            machine.pressButton();
        } catch (MachineWarning e) {
            System.out.println("Test 3:" + e.getMessage());
        }
        //Test Four 
        try {
            machine.insertCoin();
        } catch (MachineWarning e) {
            System.out.println("Test 4:" + e.getMessage());
        }
    }
}

- nitesh.kedia5 June 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

how are you changing states?pl.s write some sample snippet on it.

- Newbie December 01, 2018 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

public class VendingMachine {

    
     class ItemNode {
        int quantity;
        int name;
        int id;
        double price;
        public ItemNode ( int quantity , int name , int id , double prices)
         {
         	// Fill it .
         }

         public String toString(){
         	return "[ ID: "+id+"name "+name+" prices "+prices+" quantity"+quantity+" ]";
         }
     }

     protected HashMap<String , ItemNode> itemLocater ;
     
     public VendingMachine(){
     	itemLocater = new HashMap<String , ItemNode>();
     }

     public void sendInstruction( String buttonId )
     {

     }

     public boolean isAvailable(String buttonId)  {

     }

     public double settleBill(double amount) {

     }

     protected List<Double> getChange(double amount){

     }

     protected boolean isChangeAvailable() {

     } 

     private List<Double> greedyChange(double amount ){

     }

     private List<Double> minimumChange(double amount)
     {

     }

 	    private List<Double> twentyFiveCentChange(double amount) {

     }
    
     public boolean isEmpty(){

     }

 }

- RohitA November 28, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

Use state design pattern

- Ra December 09, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

classes
class Item < describes the various items in the vending machine>
class ProductCode < to select which drink/snack you want>
class Coin < to accept coins>
class Refund < to return remainder coins>
class Stock < to keep track of the vending machine stock for each product>
class Bagel, Donut, Energy bar, Chocolates extends class Item

- Abhijit November 09, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 votes

Do we really need to create separate classes for different items ? Can't a String field in item class do ?

- coolraj334 December 03, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Scanner;
import java.util.Set;

public class Vending {

LinkedHashMap<String,Double> hm = new LinkedHashMap<String, Double>();

Scanner s = new Scanner(System.in);

private double val;

private String key;

private static int quarters;

private static double dollar;

public void snacks() {
HashSet<String> sm = new HashSet<String>();
hm.put("Lays",2.0);
hm.put("Biscut",1.25);
hm.put("Chocklate", 1.5);
sm.add("Exit");
Set <String> keys = hm.keySet();
for(String s : keys) {
System.out.println(s+":"+hm.get(s));

}
for(String s : sm) {
System.out.println(s);
}
System.out.print("Enter Your Snack Item Name:");
key = s.next();
System.out.println("You have selected"+" "+key);
val = dollar - hm.get(key);
System.out.println(val);
if(key == "Exit") {
item();
}


}
public void drinks() {
HashSet<String> ms = new HashSet<String>();
hm.put("Coke", 3.50);
hm.put("Sprite", 2.5);
hm.put("Pepsi", 2.0);
ms.add("Exit");
Set <String> keys = hm.keySet();
for(String s : keys) {
System.out.println(s+":"+hm.get(s));

}
for(String s : ms) {
System.out.println(s);
}
System.out.print("Enter your Drink Item Name:");

key = s.next();
System.out.println("You have selected"+" "+key);
val = dollar - hm.get(key);
if(key == "Exit") {
item();
}
}
public void item() {
HashSet<String> hs = new HashSet<String>();
hs.add("Snacks<1>");
hs.add("Drinks<2>");
hs.add("Exit<3>");
for(String s : hs) {
System.out.println(s);
}
System.out.print("Enter Your Option:");
int m = s.nextInt();


switch (m) {
case 1:
snacks();
break;
case 2:
drinks();
break;
case 3:
System.out.print("Take your Money $"+dollar);
System.exit(0);

}
if(val == 0){

System.out.println("Thank you for coming have fun");



}

else if(val < 0){

System.out.println("You have Insfficient funds");

}

else if(val > 0){

System.out.println(" Balance:$"+val);

repeat();

}
}


private void repeat() {
System.out.print("Do you Want Anything Else(Y/N):");



char c = s.next(".").charAt(0);

if(c == 'y'){

if(val<0){

System.out.println("Insufficient funds");
}

else { dollar = val;}



item(); repeat(); }

else if(c == 'n'){

System.out.println("Take your Balance:$"+val);}
System.exit(0);

}
public static void main(String[] args) {

Vending ven = new Vending();

System.out.println("Welcome to the Locket Vending Machine");

System.out.print("Insert Quarters :");

@SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
Vending.quarters = s.nextInt();
Vending.dollar = 0.25*quarters;
System.out.println("You Have Inserted $"+Vending.dollar);
ven.item();


}

}

- Tarun Merla August 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

// Amount $1 - 99
public int getCoins(int amount){
		
		int total=0,quater=0,dimes=0,nickle=0,cent=0;	
			
		
		if(amount==0){
			return 0;
		}
		
		quater  = amount/25;
		dimes = amount%25/10;
		nickle = amount%25%10/5;
		cent = amount%25%20%5;
		
	System.out.println("quater:"+quater);
	System.out.println("dimes:"+dimes);
	System.out.println("nickle:"+nickle);
	System.out.println("cent:"+cent);
		
	total = quater+dimes+nickle+cent;
	System.out.println("total no.of required coins:"+total);
	return total;
	}

- Jayakesavan (JK) October 29, 2014 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More