In: Computer Science
java Programming Problem 2: Pez Candy
You may like the Pez candies and the wonderful dispensers that can be customized in so many ways. In each plastic container of Pez candy, the candies are of different colors, and they are stored in random order. Assume that you like the red candies only. Take a Pez dispenser, take out all candies one by one, eat the red ones, and put the others in a spare container you have at hand. Return the remaining candies in the initial container.
Your Tasks:
Hints
Save the below file as "PezCandy.java"
import java.util.*;
public class PezCandy {
private String[] list; // array of string to contains candy
private int size; // size of candies
private int index; // current index
// constructor
public PezCandy(int s) {
this.size = s;
this.index = 0;
this.list = new String[this.size];
}
// add candy in stack
public void add(String str) {
if (this.index < this.size) {
this.list[this.index++] = str;
}
}
// size of stack
public int getSize() {
return this.index;
}
// pop the last candy from stack
public String pop() {
if (this.index > 0) {
String ret = this.list[this.index - 1];
this.index--;
return ret;
}
return "";
}
// if stack is empty or not
public boolean isEmpty() {
return this.index == 0;
}
// to display candy stack
public String toString() {
String ret = "Candy stack:\n";
for (int i = this.index - 1; i >= 0; i--) {
ret += "\t" + this.list[i] + "\n";
}
return ret;
}
}
Save the below file as "PezCandyDriver.java"
import java.util.*;
public class PezCandyDriver {
public static void main(String[] args) {
Random rand = new Random();
// pez candy with size 12
PezCandy pc = new PezCandy(12);
for (int i = 0; i < 12; i++) {
int r = rand.nextInt(5);
String val = "";
// random candy add in stack
if (r == 0) {
val = "red";
}
if (r == 1) {
val = "yellow";
}
if (r == 2) {
val = "green";
}
if (r == 3) {
val = "pink";
}
if (r == 4) {
val = "blue";
}
pc.add(val);
}
// original stack
System.out.println("The original contenet of the Pez container");
System.out.print(pc);
PezCandy pc1 = new PezCandy(12);
// eat red candies
while (pc.isEmpty() == false) {
String candy = pc.pop();
if (candy.equals("red")) {
System.out.println("I am just eating red candy!!!");
} else {
pc1.add(candy);
}
}
System.out.println("The spare dispenser");
System.out.print(pc1);
while (pc1.isEmpty() == false) {
String candy = pc1.pop();
pc.add(candy);
}
// display the container
System.out.println("The content of Pez container after eating red candies");
System.out.print(pc);
}
}
Make sure to save both files in the same folder
//SAMPLE OUTPUT
PLEASE LIKE IT RAISE YOUR THUMBS UP
IF YOU ARE HAVING ANY DOUBT FEEL FREE TO ASK IN COMMENT
SECTION