For an assignment we are applying what is said in the title. i have written all the code out, but when I am compiling the code i get four errors dealing with the line 19 of code.
while(!myQueue<String>.isEmpty() & !myStack.isEmpty()){
this is the full code if it also helps
import java.util.*;
public class Palindrome{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String userInputConversion;
String userInput;
MyStack myStack = new MyStack();
MyQueue<String> myQueue = new MyQueue<String>();
System.out.println("Enter in a possible Palindrome. ");
userInputConversion = scan.next();
userInput = userInputConversion.toLowerCase();
String s = new String();
for(int i = 0; i < userInput.length(); i++){
s = "" + userInput.charAt(i);
System.out.print(s);
myQueue.enqueue(s);
myStack.push(s);
}
while(!myQueue<String>.isEmpty() & !myStack.isEmpty()){
String deQueued = myQueue.dequeue();
String popped = myStack.pop();
if(deQueued == popped)
System.out.println("Input is a palindrome. ");
else
System.out.println("input isnt a palindrome. ");
}
}
}
class MyStack{
private String[] stack;
private int top;
public MyStack(){
stack = new String [100];
top = 0;
}
public String push(String pushP){
if(top >= stack.length){
System.out.println("Error: MyStack.push(): stack overflow");
return "yes";
}
stack[top] = pushP;
top++;
}
public String pop(){
if(top <= 0){
System.out.print("Error in MyStack.pop(): stack empty");
return "n";
}
top--;
return stack[top];
}
public boolean isEmpty(){
if(top == 0){
return true;
}
else{
return false;
}
}
`}
class MyQueue<String> implements Iterable<String> {
private String[] queue;
private int front = 0;
private int rear = 0;
private int currentSize = 0;
public MyQueue(){
queue = (String[])(new Object[1]);
front = 0;
rear = 0;
currentSize = 0;
}
public boolean isEmpty() {
return (currentSize == 0);
}
public int currentSize() {
return currentSize;
}
public void enqueue(String String) {
if (currentSize == queue.length - 1) {
resize(2 * queue.length);
}
queue[rear++] = String;
if (rear == queue.length) {
rear = 0;
}
currentSize++;
}
public String dequeue() {
if (this.isEmpty()) {
throw new RuntimeException("Tried to dequeue an empty queue");
}
else {
String itemToReturn = queue[front];
queue[front++] = null;
currentSize--;
if (front == queue.length) {
front = 0;
}
if (currentSize == queue.length / 4) {
resize(queue.length / 2);
}
return itemToReturn;
}
}
private void resize(int capacity) {
String[] newArray = (String[]) new Object[capacity];
for (int i = 0; i < currentSize; i++) {
newArray[i] = queue[(front + i) % queue.length];
}
queue = newArray;
front = 0;
rear = currentSize;
}
}
if anyone can help that would be great or give some pointers.
For your 2nd compilation error, The type MyQueue<String> must implement the inherited abstract method Iterable<String>.iterator(), you can either
implement the public Iterator<String> iterator() method
remove the implements Iterable<String> statement
or make MyQueue abstract
Making MyQueue abstract won't help you much & I also don't see any place in the code where you need an iterator or make use of the fact that MyQueue is Iterable. Being a queue, you would want to use its signature methods - enqueue & dequeue. So, you can safely go for option 2. Else to implement, this answer should help.
You also haven't implemented the concept of type arguments perfectly. You would want to use a Type Parameter in the class definition; e.g. class MyQueue<String> becomes class MyQueue<T>. Likewise the member variables & methods would also change.
You 3rd compilation error, This method must return a result of type String is simply because your push() method doesn't have a return statement at the end. It's better to simply make it void, since you're not using the returned String "yes" anywhere. For StackOverflow, you can throw an RuntimeException, just like you did in your dequeue.
Few pointers
You've made the classic mistake of comparing Strings with == instead of .equals() in the statement if (deQueued == popped).
Make it a practice to close your scanner/resources, even though in this case there's no harm.
You have a little logical error in your while loop that compares the characters - I'll let you figure that one out.
First of all your making things Complex, for a simple string why do you want use stack or queue . i guess below logic would help you
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
Related
import java.util.Scanner;
class ed {
int fr, r;
int q[];
int n;
ed(int x) {
n = x;
fr = -1;
r = -1;
q = new int[n];
}
void enque(int n) {
int val = n;
while (r < n-1) {
if (r==n-1) {
System.out.println("Overflow");
break;
}
else if (fr==-1 && r==-1) {
fr=0;
r=0;
q[r] = val;
}
else {
r += 1;
q[r] = val;
}
}
}
void deque() {
if (fr==-1 && r==-1) {
System.out.println("Underflow");
}
else if (fr==r) {
fr=-1;
r=-1;
}
else {
fr += 1;
}
}
void reverse(int[] q) {
int a = q[0];
deque();
reverse(q);
enque(a);
}
void printq() {
for (int i = fr; i<=r; i++) {
System.out.print(q[i] + " ");
}
}
}
public class q1 {
static Scanner f = new Scanner (System.in);
public static void main(String[] args) {
int n = f.nextInt();
ed que = new ed(n);
for (int i=0; i<n; i++) {
int x = f.nextInt();
que.enque(x);
}
// que.deque();
// que.printq();
que.reverse(que.q);
}
}
My aim is to reverse a queue (Array) using a recursive function, but in VS Code, the loop is running infinite times and I'm not getting a chance to see the error. I'd like to know my mistake, and any improvement is highly appreciated.
The class ed contains a constructor which initializes the array and the front, rear values. Enque method adds an element to the queue at the rear, deque method removes the front element. Reverse method takes an array input (queue), stores the foremost element in the variable a, deques it, calls itself, then enques it at the back. VS Code is showing the error at line 48 (reverse(q), when it calls itself) but it's not showing the error as it's so far up.
A lot of things are not going the right way in your queue implementation using arrays.
Like, in enque function, you can fill values from rear = 0 to rear = n - 1, because you have n positions available in the q array.
Your code was too long, unstructured, and a bit messy with no proper variable names, So, I didn't read it any further.
But one thing I can make out is that you need to read how to implement a queue using the array.
Now, coming to queue reversal using the recursion part.
Your approach was correct, you just missed out the base case condition.
Steps for reversing queue:
Your queue has some elements, we get the first element out of the queue.
Then, we assume I have a recursive function that reverses the rest of the queue.
In this reversed queue, I just have to push that first element to the back.
And coming to the base case, each time queue size is decreasing by 1, so at the end, the queue will become empty then we don't have to do anything, just return. THUS STOPPING THE RECURSION (which you missed).
Here, is my implementation if you need some reference:
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class Queue {
private int front, rear, capacity;
private int queue[];
Queue(int c) {
front = rear = 0;
capacity = c;
queue = new int[capacity];
}
int size() {
return rear - front;
}
void enqueue(int data) {
if (capacity == rear) {
System.out.printf("Queue is full.\n");
return;
}
else {
queue[rear] = data;
rear++;
}
}
void dequeue() {
if (front == rear) {
System.out.printf("Queue is empty.\n");
return;
}
else {
for (int i = 0; i < rear - 1; i++) {
queue[i] = queue[i + 1];
}
if (rear < capacity)
queue[rear] = 0;
rear--;
}
}
int front() {
if (front == rear) {
System.out.printf("\nQueue is Empty.\n");
return -1;
}
return queue[front];
}
void print() {
int i;
if (front == rear) {
System.out.printf("Queue is Empty.\n");
return;
}
for (i = front; i < rear; i++) {
System.out.printf(" %d, ", queue[i]);
}
System.out.println("");
return;
}
}
class GFG {
static Scanner scanner = new Scanner(System.in);
public static void reverseQueue(Queue queue) {
if (queue.size() == 0) {
return;
}
int frontElement = queue.front();
queue.dequeue();
reverseQueue(queue);
queue.enqueue(frontElement);
}
public static void main (String[] args) {
int queueSize = scanner.nextInt();
Queue queue = new Queue(queueSize);
for (int i = 0; i < queueSize; i++) {
int element = scanner.nextInt();
queue.enqueue(element);
}
queue.print();
reverseQueue(queue);
queue.print();
}
}
You can comment if anything is wrong, or need more clarification.
The task is to implement a generic stack (can not use the libraries from java), make the user input an expression using true and false for booleans b1 and b2, logical operators (and, or, not, iff, implies) recognize if its boolean or operator and send to 2 stacks, then poping the stacks to evaluate if its a valid expression, i.e: input:(b1 and b2) implies b3 is a valid expression but B3 and (b2 or) is not, I have issues with the stack part, since the peek is not returning any element, here is my code so far, note: the charat is because I would be checking that the brackets are balanced as well:
public class MyStack<T> {
class StackOverFlowException extends RuntimeException{}
class EmptyStackException extends RuntimeException{}
private T[] stack;
private int top;
public MyStack(int size) {
this.stack = (T[]) new Object[size];
this.top = 0;
}
public boolean isEmpty() {
return this.top == 0;
}
public boolean isFull() {
return this.top == stack.length;
}
public void push(T x) {
if(top == stack.length) {
throw new StackOverFlowException();
}
else {
this.stack[top] = x;
top++;
}
}
public T pop() {
if(isEmpty()) {
throw new EmptyStackException();
}
else {
T value = this.stack[--top];
return value;
}
}
public T peek() {
return this.stack[top];
}
public static void main(String[] args) {
MyStack<String> tf = new MyStack(100);
MyStack<String> operators = new MyStack(100);
System.out.println("Please input the expression to evaluate: ");
Scanner scn = new Scanner(System.in);
String expression = scn.nextLine();
String tokens[] = expression.split(" ");
int n = tokens.length;
boolean P1 = true;
boolean P2 = true;
boolean result = true;
for(int i = 0; i < n; i++ ) {
String separate = tokens[i];
char x = separate.charAt(i);
if(tokens[i].equalsIgnoreCase("true")||tokens[i].equalsIgnoreCase("false")) {
tf.push(separate);
tf.peek();
}
else if(tokens[i].equalsIgnoreCase("and")||tokens[i].equalsIgnoreCase("not")||tokens[i].equalsIgnoreCase("or")||tokens[i].equalsIgnoreCase("implies")||tokens[i].equalsIgnoreCase("iff")) {
operators.push(separate);
}
else {
System.out.println("Expression not Valid!");
}
}
}
The top variable is being misinterpreted in the peek() method (as well as the isEmpty() method).
As implemented, top is a misnomer since it is actually the size of the stack (which may also be considered the index for the next element to be pushed). So your peek() method should be looking at the element before top.
Alternatively, you may to define top as the element at the top of the stack, as this is generally how you are using it elsewhere. In this case, you will need to define a flag value to indicate the stack is empty.
In any case, you need handle the empty Stack case in the peek() method.
public class MyStack {
private static final int EMPTY = -1;
private int top = EMPTY;
... other stuff ...
public boolean isEmpty() {
return EMPTY == top;
}
public T peek() {
if (ifEmpty()) {
throw new EmptyStackException("Cannot peek into empty Stack");
}
return stack[top];
}
}
This code is for learning generic class and stack operation.
but it has some error about declare variable type
package lab11_2_590510535;
import java.util.Scanner;
class Queue <TYPE>{
private int count;
private int front;
private int rear;
private int n;
private Object [] item;
private TYPE queueFront;
static void pl(Object a){System.out.println(a);}
static void p(Object a){System.out.print(a);}
Queue(int x){
n = x;
item = new Object[n];
front = 0;
rear = -1;
count = 0;
}
public boolean isEmpty(){
for(int i = 0 ; i<item.length ; i++){
if(item[i] != null){return false;}
}
return true;
}
public boolean isFull(){
if(item[item.length] != null){return true;}
else{return false;}
}
public void enqueue(TYPE v){
if(!isFull()){
if(rear < n-1){
rear++;
item[rear] = v;
count++;
}
}else{pl("Queue is Full.");}
}
public TYPE dequeue(){
if(!isEmpty()){
queueFront = item[front];
front++;
count++;
}else{p("Queue is empty.");}
return queueFront;
}
public void show(){
for(int i = 0 ; i <item.length ; i++){
if(item[i] != null){p(item[i] + ", ");}
}
}
public class Lab11_2_590510535 {
static void pl(Object a){System.out.println(a);}
static void p(Object a){System.out.print(a);}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner keyboard = new Scanner(System.in);
char choice;
int N;
p("Enter N: ");
N = keyboard.nextInt();
p("Choice input type; int(1) , char(2): ");
choice = keyboard.next().charAt(0);
if(choice == '1'){Queue <Integer> q = new Queue(N);}
else if(choice == '2'){Queue <Character> q = new Queue(N);}
do{
pl("1) enqueue"); pl("2) dequeue"); pl("3) show"); pl("4) exit");
p("Enter function number : ");
choice = keyboard.next().charAt(0);
if(choice == '1'){
p("Enter data: ");
Object s = keyboard.next();
q.enqueue(s);
}
else if(choice == '2'){Object s = q.dequeue();
pl(s);
}
else if(choice == '3'){q.show();}
}while(choice != '4');
}
}
1.After user input choice and I create generic object with type casting in do...while loop it can't find "q".
2.In public TYPE dequeue() method line "queueFront = item[front];" Object can't be convert to TYPE ,how can I fix it.
Try to change private Object [] item to private TYPE [] item. Also you will need to know how to create a generic array for your example:
How to create a generic array?
How to create a generic array in Java?
You will need to change item = new Object[n]; to item = (TYPE[]) new Object[n];
However you should avoid creating generic types and instead you should inject them or use a factory to create them.
Here i have create a delete method that will search through the Object array and remove the selected object.
public class DogList {
private int numItems;
private DogItem[] dogListArray;
private int position;
private String name;
DogList () {
numItems=0;
position = 0;
dogListArray = new DogItem[20];
}
DogList(String name) {
this.name = name;
}
public void deleteItem(DogList gi) {
int i = 0;
while( (i < numItems) && (gi != dogListArray[i]) ) {
i++;
}
if(i == numItems) {
// Throw exception if there is not matching Item
throw new NoSuchElementException("That item does not exists");
}
int pos = i;
while(pos < numItems -1 ) {
dogListArray[pos] = dogListArray[pos + 1];
pos++;
}
numItems --;
}
I cant wrap my head around why in the first while loop the (gi != dogListArray[i]) is throwing an error:"Incompatible operand types DogList and DogItem"
Any help would be wonderful.
The code is pretty long so if you want to see any part i will edit and show what is needed.
I am assuming that dogListArray is a DogItem[], making dogListArray[i] a DogItem. I assume that gi is meant to be a DogItem as well rather than a DogList?
On a separate but still relevant note, you should use the equals method, rather than == or !=, to compare objects. See here an explanation of this aspect.
Here is the beginning of my code from my sub class RECORD.
class Record {
private int shares;
private int pricePerShare;
// constructor
Record(int sharesNewValue, int pricePerShareNewValue) {
shares = sharesNewValue;
pricePerShare = pricePerShareNewValue;
}
// inspectors
public int getShares() {
return shares;
}
public int getPricePerShare() {
return pricePerShare;
}
// modifiers
public void setShares(int sharesNewValue) {
shares = sharesNewValue;
}
public void setPricePerShare(int pricePerShareNewValue) {
pricePerShare = pricePerShareNewValue;
}
}
And I want to access the value of shares in my main method that is in a different class.I have the RECORD class linked to another subclass named QUEUE. And in my main method, I have a link to QUEUE with this:
class Lab04a {
public static Queue Q = new Queue();
}
Later on in the code, I need to subtract an int value from the SHARES variable in the Record class, but because that is of type Record, I have no clue how to do this!
I'm not sure if I was clear enough when explaining this, should you have any further questions I'll be more than happy to reply.
Thank you.
Due to my inability to coherently state what I'm trying to accomplish in this lab assignment, I'll just post my other two classes in their entirety:
class Queue {
private int count; // number of elements in the queue
private int head; // index of head element, -1 if queue is empty
private int tail; // index of tail element, -1 if queue is empty
private int MAXSIZE = 1; // Physical size of the queue. DO NOT CHANGE!
private Record[] array; // circular array to store the elements of the queue
// constructor
Queue() {
count = 0;
head = -1;
tail = -1;
array = new Record[MAXSIZE];
}
// inspectors
public boolean empty() {
// Returns true if the queue is empty. Otherwise returns false.
return (count != 0);
}
public int size() {
// Returns the number of elements in the queue
return count;
}
public Record front(){
// Returns the head element of the queue if the queue is not empty.
// Otherwise returns a Record with its data parts set to -1.
if (count == 0)
return new Record(-1, -1);
else
return array[head];
}
public Record rear(){
// Returns the tail element of the queue if the queue is not empty.
// Otherwise returns a Record with its data parts set to -1.
if (count ==0)
return new Record(-1, -1);
else
return array[tail];
}
public String toString() {
// Returns the elements of the queue
String str = "< ";
int h = head;
for (int i = 0; i < count; i++){
str += "(" + array[h].getShares() + ", " + array[h].getPricePerShare() + ") ";
h = (h+1) % MAXSIZE;
}
str += ">";
return str;
}
// modifiers
public boolean dequeue() {
// Removes the head element of the queue.
if (count == 0)
return false;
if (count == 1) {
count = 0;
head = -1;
tail = -1;
}
if (count > 1){
head = (head + 1) % MAXSIZE;
count--;
}
return true;
}
public void enqueue(Record element) {
// Enqueues element to the tail of the queue.
//if max size is reached, it doubles the size to allow for more values
if (count == MAXSIZE) {
Record[] array2 = new Record[MAXSIZE * 2];
for (int i = 0; i < count; i++) {
array2[i] = array[i];
}//closes for loop
array = array2;
MAXSIZE *= 2;
}
tail = (tail + 1) % MAXSIZE;
array[tail] = element;
if (count == 0)
head = tail;
count++;
}//close enqueue method
}//closes class
And then here is my MAIN parent class:
class Lab04a {
public static Queue Q = new Queue(); // creates global object
public static Record R = Record;
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int option, buyPrice, buyShares, sellPrice, sellShares, totalShares, totalValues, totalSellPrice;
option = 0;
totalShares = 0;
totalValues = 0;
Queue Q2 = Q;
while (option != 3) {
System.out.print("Enter option (1:buy, 2:sell, 3:quit): ");
option = scan.nextInt();
if (option == 1) {
System.out.print("Enter shares to buy and price per share: ");
buyShares = scan.nextInt();
buyPrice = scan.nextInt();
Record r = new Record(buyShares, buyPrice);
Q.enqueue(r);
totalShares = totalShares + buyShares;
totalValues = totalValues + (buyShares * buyPrice);
}// ends if
if (option == 2) {
System.out.print("Enter shares to sell and price per share: ");
sellShares = scan.nextInt();
sellPrice = scan.nextInt();
totalSellPrice = sellPrice * sellShares;
if (sellShares > totalShares) {
System.out.println("You do not own enough shares for this sale.");
}
for (int i = sellShares; i > 0; ) {
if (sellShares == Q.front().getShares()) {
i -= Q.front().getShares();
Q.dequeue();
}
if (sellShares < Q.front().getShares()){
Record minus;
minus = Q.front() - sellShares;
Q.front().setShares(minus);
Q.front().setShares(Q.front().getShares());
i -= sellShares;
}
}
}// ends if
// Prints content of Queue
System.out.println("Queue: " + Q.toString());
System.out.println("Total Shares: " + totalShares);
System.out.println("Total Shares Value: $" + totalValues);
System.out.println();
}// ends while loop
System.out.println(Q.toString());
}// ends main method
}
If I understand your question, you can add accessor and mutator methods (or getters and setters)
private int shares;
private int pricePerShare;
public int getShares() {
return shares;
}
public void setShares(int shares) {
this.shares = shares;
}
public int getPricePerShare() {
return pricePerShare;
}
public void setPricePerShare(int pricePerShare) {
this.pricePerShare = pricePerShare;
}
Edit
To use it,
Record record = Q.front(); // <-- I assume your Q contains Record(s).
if (record.getShares() >= sellShares) {
record.setShares(record.getShares() - sellShares); // <-- for example
}
Make sure Q.front() is a method that returns a Record.
If that is true, you should be able to use the line
Q.front().setShares(Q.front().getShares()-MINUS_VALUE))