I'm working on the hotel program and I have a problem with the my Queue class.
I need to create queue object in my program to add to queue and take from queue. Every time a name is added to a room it should use the queue object method to add the customer’s name to the queue. When the user selects to display the names of the first 3 customers my code should remove them from the queue one by one (first in first out) and display them as they are removed.
The queue should be based on an array. When the queue items reach the end of the array they should be added to the start or the array. If the queue becomes full the oldest queue item should be automatically removed and displayed.
The problem at the moment is when the end reaches 5 it should push the first input and take the last input and move it to the front of an array. Also please note the Queue must be based on string array. Please see the code i have so far, maybe some of you can help?
public class Queue {
static String qitems[] = new String[7];
static int front = 0, end = 0;
void addqueue(String name) {
System.out.println("Enter Queue Item :");
qitems[end] = name;
end++;
if(end==5){
takequeue(name);
}
}
void takequeue(String name) {
qitems[front]=name;
if (end > front) {
System.out.println("Item taken :" + qitems[front]);
front++;
} else {
System.out.println("Empty queue");
}
}
void displayqueue() {
System.out.println("Queue display: ");
for (int look = front; look < end; look++) {
System.out.println(" " + qitems[look]);
System.out.println("end"+end);
}
System.out.println("");
}
The addqueue() seems to have a logical flaw. Value of end gets increased by 1 before you check if(end==5). When the value of end becomes 6, the if statement is ignored, the takequeue() method is not invoked and you face the problem. To solve this, either add the if statement before end++ as
void addqueue(String name){
System.out.println("Enter Queue Item :");
qitems[end] = name;
if(end==5){
takequeue(name);
}
end++;
}
Or check for end>=5 rather than end==5 as:
void addqueue(String name){
System.out.println("Enter Queue Item :");
qitems[end] = name;
end++;
if(end>=5){
takequeue(name);
}
}
P.S. Please be more precise and clearer while asking a question from next time by using proper punctuation in your question description. Also see the How to ask questions section in the FAQ.
Related
As title says I need to do the following. But I somehow am getting the wrong answer, perhaps something with the loops is wrong?
And here's what I have coded so far, but it seems to be giving me the wrong results. Any ideas, help, tips, fixes?
import java.util.ArrayList;
public class pro1
{
private String lettersLeft;
private ArrayList<String> subsets;
public pro1(String input)
{
lettersLeft = input;
subsets = new ArrayList<String>();
}
public void createSubsets()
{
if(lettersLeft.length() == 1)
{
subsets.add(lettersLeft);
}
else
{
String removed = lettersLeft.substring(0,1);
lettersLeft = lettersLeft.substring(1);
createSubsets();
for (int i = 0; i <= lettersLeft.length(); i++)
{
String temp = removed + subsets.get(i);
subsets.add(temp);
}
subsets.add(removed);
}
}
public void showSubsets()
{
System.out.print(subsets);
}
}
My test class is here:
public class pro1
{
public static void main(String[] args)
{
pro1s = new pro1("abba");
s.createSubsets();
s.showSubsets();
}
}
Try
int numSubsets = (int)java.lang.Math.pow(2,toSubset.length());
for (int i=1;i<numSubsets;i++) {
String subset = "";
for (int j=0;j<toSubset.length();j++) {
if ((i&(1<<j))>0) {
subset = subset+toSubset.substring(j,j+1);
}
}
if (!subsets.contains(subset)) {
subsets.add(subset);
}
}
where toSubset is the string that you wish to subset (String toSubset="abba" in your example) and subsets is the ArrayList to contain the results.
To do this we actually iterate over the power set (the set of all subsets), which has size 2^A where A is the size of the original set (in this case the length of your string).
Each subset can be uniquely identified with a number from 0 to 2^A-1 where the value of the jth bit (0 indexed) indicates if that element is present or not with a 1 indicating presence and 0 indicating absence. Note that the number 0 represents the binary string 00...0 which corresponds to the empty set. Thus we start counting at 1 (your example did not show the empty set as a desired subset).
For each value we build a subset string by looking at each bit position and determining if it is a 1 or 0 using bitwise arithmetic. 1<<j is the integer with a 1 in the jth binary place and i&(i<<j) is the integer with 1's only in the places both integers have a 1 (thus is either 0 or 1 based on if i has a 1 in the jth binary digit). If i has a 1 in the jth binary digit, we append the jth element of the string.
Finally, as you asked for unique subsets, we check if we have already used that subset, if not, we add it to the ArrayList.
It is easy to get your head all turned around when working with recursion. Generally, I suspect your problem is that one of the strings you are storing on the way down the recursion rabbit hole for use on the way back up is a class member variable and that your recursive method is a method of that same class. Try making lettersLeft a local variable in the createSubsets() method. Something like:
public class Problem1
{
private String originalInput;
private ArrayList<String> subsets;
public Problem1(String input)
{
originalInput = input;
subsets = new ArrayList<String>();
}
// This is overloading, not recursion.
public void createSubsets()
{
createSubsets(originalInput);
}
public void createSubsets(String in)
{
if(in.length() == 1)
{
// this is the stopping condition, the bottom of the rabbit hole
subsets.add(in);
}
else
{
String removed = in.substring(0,1);
String lettersLeft = in.substring(1);
// this is the recursive call, and you know the input is getting
// smaller and smaller heading toward the stopping condition
createSubsets(lettersLeft);
// this is the "actual work" which doesn't get performed
// until after the above recursive call returns
for (int i = 0; i <= lettersLeft.length(); i++)
{
// possible "index out of bounds" here if subsets is
// smaller than lettersLeft
String temp = removed + subsets.get(i);
subsets.add(temp);
}
subsets.add(removed);
}
}
Something to remember when you are walking through your code trying to think through how it will run... You have structured your recursive method such that the execution pointer goes all the way down the recursion rabbit hole before doing any "real work", just pulling letters off of the input and pushing them onto the stack. All the "real work" is being done coming back out of the rabbit hole while letters are popping off of the stack. Therefore, the first 'a' in your subsets list is actually the last 'a' in your input string 'abba'. I.E. The first letter that is added to your subsets list is because lettersLeft.length() == 1. (in.length() == 1 in my example). Also, the debugger is your friend. Step-debugging is a great way to validate that your code is actually doing what you expect it to be doing at every step along the way.
I have an assignment in Java to make a vending machine that displays items and prices using the printf tool and requests the user to enter the money they have. It then asks the user to make a selection with a character, exiting if they type x and prompting for another try if they type in an invalid character. It also keeps a running total of the money they have left and doesn't allow them to buy something they don't have the money for. After user 1 is done, it is then open for the next user to enter the amount of money they have and choose an item but with the items the first user chose absent. This cycle repeats until nothing is left in the machine or a user ends the program. Each user should be able to buy as many of each item as they want (one by one) until there is no more of that item.
I'd use a class to indicate a type of item.
public class Item { // or without public
private String name;
private char choice;
private double price;
private int amount; // or name it *quant*-what I can't spell that word
// Constructors, getters, setters, etc.
}
And you can use a list to handle them. This initializes items in the vender:
List<Item> items = new ArrayList<>();
items.add(new Item("Milk", 'a', 2.00, 5));
// Add other items
And this prints all items:
for(Item item : items)
System.out.printf(/* format string */, item.getName(), /* other arguments */);
And this handles actual purchase:
boolean foundItem = false;
for(Item item : items) {
if(item.getChoice() == choice) {
foundItem = true;
// Handle not enough money, not enough amount, etc. or sell it
}
}
if(!foundItem) {
// Invalid entry
}
And this it our main:
public static void main(String s) {
// Initialize items in the vender
// Initialize other things needed
while(/* has items to sell */) {
// Read a double as customer's money
// `break;` if is a program-exit request
while(true) {
// Print current items
// Read a character as customer choice, to lower case
// `break;` if is an customer-exit request
// Handle the actual purchase request
}
// Print customer exit message
}
// Print program exit message
}
Well, it's your responsibility to fill in the blank.
It seems like your while(choice==...) loop never ends.
The variable choice is never altered within the loop and so once you get in you'll never come out.
You should be prompting the user to enter a new choice inside the loop.
I'm stuck on how to write a delete method for a menu (object orientation) program I am writing. The menu gives the user the option to delete the last name entered on the program. I'm completely stuck on this part! Would be greatly appreciated if you guys/gals could show me a simple delete method!
Many Thanks!
This is my code so far for Adding a Name:
public static int addOne(String theArray[], int location, String theName, int noofvalues)
{
int step;
if(noofvalues == 0)
{
theArray[0] = theName;
noofvalues++;
}
else
{
for(step = noofvalues - 1; step >= location; step--)
{
theArray[step + 1] = theArray[step];
}
theArray[location] = theName;
noofvalues++;
}
return noofvalues;
}
Since it looks like homework, I won't provide any code at all (otherwise, I would solve the homework and you won't learn anything), only ideas an possibly an algorithm to do it.
Store the last name inserted by the user in a variable. Let's say, this variable is lastInsertedName.
Go through all the elements in your array and search this String in it. When you find lastInsertedName in the array, store the index in a variable, let's say indexFound and stop the loop.
If indexFound is greater or equals than 0:
Move all the elements starting at indexFound in the array one position back.
Decrease the variable that acts as the size of your array.
Use List:
public static int addOne(List names, int location, String theName, int noofvalues)
{
names.add(location, theName);
return names.size();
}
public static void deleteOne(List names, int location){
names.remove(location);
}
Here is a question about Stack on StackOverflow.
My question might seem very very vague but if you check my program which I have written then you might understand what I am trying to ask.
I have implemented the stack myself. I present the user with 3 choices. Push, Pop and View the stack. When view(display) method is called then bunch of 0s show instead of nothing. We know the stack contains nothing unless we put something on it. But since my implemented stack is stack of integers using array, the display method when called shows bunch of 0s(the default values of integers in the array). How do I show nothing instead of 0s. I know I can add ASCII for whitespace character but I think it would still violate the rule of stack(Stack should be empty when there is not element, not even code for whitespace).
Here is my program:
import java.util.Scanner;
public class StackClass
{
public static void main(String []args)
{
Scanner input=new Scanner(System.in);
int choice=0;
int push;
Stack stack=new Stack();
do
{
System.out.println("Please select a stack operation:\n1. Press 1 for adding to stack\n2. Press 2 for removing elements from stack\n3. View the stack");
choice=input.nextInt();
switch(choice)
{
case 1:
System.out.println("Please enter the number that you want to store to stack");
push=input.nextInt();
stack.push(push);
case 2:
stack.pop();
case 3:
stack.display();
}
}
while((choice==1)||(choice==2)||(choice==3));
}
}
class Stack
{
private int size;
private int[] stackPlaces=new int[15];
private int stackIndex;
Stack()
{
this.size=0;
this.stackIndex=0;
}
public void push(int push)
{
if(size<15)
{
stackPlaces[stackIndex]=push;
size++;
stackIndex++;
}
else
{
System.out.println("The stack is already full. Pop some elements and then try again");
}
}
public void pop()
{
if(size==0)
{
System.out.println("The stack is already empty");
}
else
{
stackPlaces[stackIndex]=0;
size--;
stackIndex--;
}
}
public void display()
{
System.out.println("The stack contains:");
for(int i=0;i<stackPlaces.length-1;i++)
{
System.out.println(stackPlaces[i]);
}
}
}
In display(), simply change your loop to use size for the loop condition, so that you display the logical number of elements:
for (int i=0;i < size; i++)
{
System.out.println(stackPlaces[i]);
}
Note that your existing loop was only showing 14 of the 15 values, too...
You initialize an array of int-s, of size 15. The int datatype defaults to 0 (as opposed to its wrapper class Integer which defaults to null), so what you are really doing is creating an int array with 15 0's. So, when you loop through the array and print its content, you will get, well, 15 0's.
The solution is, as implied by others, exchange the loop limitation to the size of the stack (the number of elements actually added), rather than the size of the array.
instead of for(int i=0;i<stackPlaces.length-1;i++), do for(int i=0;i<stackIndex;i++)
I'm working on a queue project where the program is simulating a grocery store. In my program, I have a method call that sets up a random variable that represents the time that it takes to service the customer in queue. The total iterations are 60, signifying minutes. Say if the first customer is given a 4 minute wait time, I need to be able to decrement the time after each minute until it reaches 0. I cannot figure out how to decrement the value stored in the queue named myQueue. Any suggestions how I can decrease the value stored in the queue after each minute?
import java.util.*;
import java.util.Random;
public class GroceryStore{
public static void main (String[] args){
int newCust=0; //to hold random variable 1-4 for 25% chance of new customer
Queue<Integer> myQueue = new LinkedList<Integer>(); //instantiates new queue
int wait = 0;
int numCust = 0; //holds counter for number of customer
for (int i = 1; i <= 60; i++) //iterator to cycle through 60 minutes
{
Random randomNum = new Random();
newCust = randomNum.nextInt(4)+1; //gives random #1-4, if 1, new cust added
if(newCust == 1) //if statement to execute code if new cust added
{
Customer cust = new Customer();
wait = cust.getServiceTime(); //stores wait time in variable
myQueue.add(wait); //adds customer to the queue by wait time
System.out.println("New customer added to queue, queue length is now " + myQueue.size());
}
if(myQueue.isEmpty()) //if to check if queue is empty and skip other conditionals
System.out.println("-----------");
else if(myQueue.peek()==0) //if top of queue is at 0, remove from queue
{
myQueue.remove();
System.out.println("Customer removed");
}
else
//THIS IS WHERE I AM TRYING TO DECREASE THE VALUE IN THE TOP QUEUE
}
Integer is immutable, so wrap an int in your own class:
class Customer {
int time;
public Customer(int time) {
this.time = time;
}
// getter, setter
}
and define a corresponding Queue:
Queue<Customer> myQueue = new ...;
Instantiate a java.util.Timer; in the corresponding java.util.TimerTask, iterate through the Queue using a for-each loop, altering or removing each in turn:
for (Customer c : myQueue) { ... }
Your wanting to decrement a value stored in the Customer object that is located at the top of the queue.
The easiest way would be to add a method to reduce the serviceTime within the Customer class.
public decServiceTime() {
serviceTime--;
}
Looking at the value associated to the Customer object sitting in the queue you can perform the actions necessary.
Also if you have any questions you should first try sending me, your TA an email. =)