I'm a computer science student that just started my sophomore programming class and I'm having some real issues with a project that deals with Stacks and collections.
Basically, this is a project that relies on the ArrayStack Class(ArrayStack, to be specific) to convert mathematical expressions between postfix and infix forms.
Basically, ArrayStack is used to take in an expression like 45 * (26 - 5) / 54, turn it into a collection, then rewrite in a postfix form like 45 26 5 - * 54 /
The problem is, first of all, whenever I try to substitute with Character in the main method(since the stack needs to store both operators and operands, maybe there's a better data type I'm missing here), I get some strange syntax error, usually involving the program thinking that ArrayStack.System is somehow a statement(System.out.println is right below an ArrayStack statement, which suggests there's some kind of syntax problem)
Here's the code I have so far:
public class ArrayStack<T> implements StackADT<T>
{
private static final int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
public ArrayStack() {
top = -1;
stack = (T[]) (new Object[DEFAULT_CAPACITY]);
}
public void push(T element) {
stack[top+1] = element;
top++;
}
public T pop() {
T element = stack[top];
stack[top] = null;
top--;
return element;
}
public T peek() {
return stack[top];
}
public boolean isEmpty() {
if(stack[0]==null)
return true;
else{
return false;
}
}
public int size() {
int length = 0;
for(int count=0;count<stack.length;count++) {
if(stack[count]!=null) {
length++;
}
else if(stack[count]==null) {
break;
}
}
return length;
}
public String toString() {
String array = "";
for(int count=0;count<stack.length;count++) {
array = array+stack[count]+" ";
}
return array;
}
}
And for the main method:
public class StackTester {
public static void main(String[] args) {
boolean quit = false;
int input;
String expression;
do {
System.out.println("1. Convert infix to postfix");
System.out.println("2. Convert postfix to infix");
System.out.println("3. Exit.");
java.util.Scanner keyboard = new java.util.Scanner(System.in);
input = keyboard.nextInt();
switch(input) {
case 1:
//ArrayStack stack = new ArrayStack();
//System.out.println("Enter an infix expression: ");
expression = keyboard.next();
for(int count=0;count<expression.length();count++) {
Character a = expression.charAt(count);
stack.push(a);
}
for(int count=stack.size()-1;count>=0;count--) {
if(stack.peek()=='+') {
}
}
}
break;
}
while(!quit);
}
}
The error usually occurs at the lines marked with //, every time I try to insert something like or otherwise, the program gives some weird syntax error like its trying to read it together with the line below it. Any ideas what's going on here?
Related
I am writing a stack data structure in java using arrays. The problem is when I try to push the users char input it doesn't display. The problem is with this code.
public static void preSuf(Stack stack) {
Scanner key = new Scanner(System.in);
System.out.println("enter the values");
while(key.hasNext()){
char c = key.next().charAt(0);
stack.push(c);
}
}
When I change the while(key.hasNext()) to if(key.hasNext()) it works but it only prints one time and doesnt itterate. How can I fix this problem thank you.
Edit: Here is the whole code
import java.util.Scanner;
public class Stack {
private int top;
private char[] container;
private int size;
public static int pos = 0;
// constructor
public Stack(int N) {
container = new char[N];
size = N;
top = 0;
}
public boolean isFull() {
return (size == top);
}
public void push(char string) {
if (!isFull()) {
container[top] = string;
top++;
} else {
return;
}
}
public int pop() {
int drop;
drop = container[top - 1];
container[top] = 0;
top--;
return drop;
}
public int peek() {
int drop2;
drop2 = container[top - 1];
return drop2;
}
public void display() {
for (int i = 0; i < container.length; i++) {
if (container[i] != 0) {
System.out.print(container[i]);
}
}
}
public static void preSuf(Stack stack) {
Scanner key = new Scanner(System.in);
System.out.println("enter the values");
while(key.hasNext()){
char c = key.next().charAt(0);
stack.push(c);
}
}
public static void main(String args[]) {
Stack stack = new Stack(3);
preSuf(stack);
stack.display();
stack.display();
System.out.println();
}
}
The problem is that you haven't written any code to actually print the contents of your stack.
You could write a loop after your while loop to iterate over the stack and print out each character.
You'll also need a way of exiting your while loop. You can do this either with a special character, eg. if(c == '.') break; or you can just press Ctrl+Z.
EDIT: Based on the edit to the question and the full code being presented, I think the suggestion of needing the extra loop is now redundant. You have that in stack.display(). You just need to get out of your while loop.
you haven't determined when the loop should end.
you'd think if you press enter without entering anything the loop
would break but that's not how next operates. if you press enter
without entering anything or input data which consists of only whitespaces, next will block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
the solution is to include a condition at which control should break out of the loop.
I'm trying to use a java Stack to push String values:names into it, derived from input from a Scanner method. I'd then want to pop the names from the stack, and after show the logical and physical elements of the stack. I believe I should be using an Array Stack but not entirely sure as I don't have much quidance or experience with Stacks.
Currently I am getting the following error when compiling the Stack.java file.
Stack.java:24: cannot find symbol
symbol : method push(java.lang.String)
location: class java.lang.String[]
stack.push(s);
I've been researching this and trying different code for days, but as I am very new to this, and I have run out of ways to manipulate the code to make it work.
I would highly appreciate some advice...tnx!
Here is my Stack Class code:
import java.lang.*;
import java.util.*;
public class Stack { //Create Class
private String stack[] ;
private int top;
private static final int SIZE = 5;
String name;
Scanner scan = new Scanner(System.in);
public Stack(int SIZE){
stack = new String [SIZE];
top = 0;
}
public void push(String s) { //Method to Insert
if (isStackFull())
System.out.println ("Stack is Full "); //If Stack full Print Full
else {
while (scan.hasNextLine()){
s = scan.nextLine();
stack.push(s);
}
stack[top] = s;
top++;
}
}
public String pop() { //Method to Delete
if (isStackEmpty())
System.out.println ("Stack is Empty "); //If Stack empty print Empty
else{
String value = stack[top];
top--;
return value;
}
return stack[top];
}
public String toString( ){ //Method print Logical Stack
if (isStackEmpty( ))
System.out.println ("Stack is Empty "); //If Stack empty print Empty
else
System.out.println("\nThe Stack");
String result = "";
for (int j=0; j < top; j++)
result = result + stack[j].toString() + "\n";
return result;
}
public boolean isStackEmpty() { //Method boolean type to check empty Stack
return (top == 0);
}
public boolean isStackFull() { //Method boolean type to check full Stack
return (top == (SIZE-1));
}
}
For the StackTest Code, generally I call the methods in Stack. Eg.
public class StackTest { //Create class
public static void main(String[] args){ //Main Method
Stack n = new Stack(); //Declare variables
Scanner in = new Scanner(System.in);
String response;
char x;
and
while(x != 'q' && x != 'Q'){ //While loop initiates if no q or Q char input
switch(x){ //Start of swtich for insert, delete, print physical, logical or default quite
case 'i':
n.push();
System.out.println ("Inserted item from Stack");
break;
case 'd':
n.pop();
System.out.println ("Deleted item from Stack");
break;
case 'p':
n.toString();
System.out.println ("Printed Physical Stack ");
break;
Your push(String s) is method is calling push() on String which is incorrect, moreover the logic for push(String s) is complicated, rather it is simple as shown below in the code with comments:
public void push(String s) {
if (isStackFull())
System.out.println ("Stack is Full "); //If Stack full Print Full
else {
stack[top] = s; //just add the string to the top of the stack
top++; //increment top
}
}
In the push method itself you are trying to call stack.push hence it is throwing error. replace the stack.push to stack[top_index]= the string.
I am doing a pretty simple program, where a user will be prompted to enter up to 80 characters. We need to build our own stack and push each character onto the stack. Then pop and display the characters in reversed order. Thought I was done, but my instructor wants me to do something if a user enters more than 80 characters. Basically, I need to ignore all characters over 80. How would I go about doing this? I have been trying to figure this out, but can't get it. I am sure it will be something simple that I completely missed. Any help, suggestions, are appreciated!
stackUser
import java.util.Scanner;
public class stackUser {
public static void main(String[] args){
System.out.println("\nPlease enter up to 80 characters and I will reverse them: ");
Scanner key = new Scanner(System.in);
String input = key.nextLine();
myStack stack = new myStack();
for(int i = 0; i < input.length(); i++){
char c = input.charAt(i);
stack.push(c);
}
if(stack.isEmpty()){
System.out.println("Stack is empty!");
}else{
while(!stack.isEmpty()){
char rev = stack.pop();
System.out.print(rev);
}
}
}
}
myStack
public class myStack {
private int max = 80;
private char[] Stack = new char[max];
private int top = -1;
public void push(char input){
top++;
Stack[top] = input;
}
public char pop(){
char popped = Stack[top];
top --;
return popped;
}
public boolean isEmpty(){
boolean empty;
if(top == -1){
empty = true;
}else{
empty = false;
}
return empty;
}
}
Handle ArrayIndexOutOfBoundsException is bad idea, you need to check current top value with max value. Because ArrayIndexOutOfBoundsException is unchecked exception, and it means that error of developer.
I would declare the push method like this to indicate that it will throw an exception if the max is reached:
public void push(char input) throws ArrayIndexOutOfBoundsException{
top++;
Stack[top] = input;
}
Then in the main method you can use a try/catch block to handle the exception:
try{
stack.push(c);
}catch (ArrayIndexOutOfBoundsException ex){
System.out.println("too much!");
}
A try catch loop around anything that will throw an IndexOutOfBounds
try {
...code here
}
catch (ArrayIndexOutOfBoundsException e) {
...whatever you want to do in event of exception
}
I need a program that reads in data and sorts the file in descending order using quicksort based on the index provided for instance this is the data using comparable
adviser,32/60,125,256,6000,256,16,128,198,199
amdahl,470v/7,29,8000,32000,32,8,32,269,253
amdahl,470v/7a,29,8000,32000,32,8,32,220,253
amdahl,470v/7b,29,8000,32000,32,8,32,172,253
amdahl,470v/7c,29,8000,16000,32,8,16,132,132
And i need to sort by the 5th index(mmax) case 2 and the 6th(cache) case 3 and the ninth index(php) case 4 in descending order & print the first index which is already sorted case 1
The problems with my code are as follows:
It doesn't sort based off the index
It gives me an error at runtime with the code: Arrays.sort(c);
Please help with suggestions
Thanks
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Prog4 {
static Scanner input;
static File filename;
/**
* This function displays the menu for the user to choose an option from
*/
public void menu() {
System.out.println("Option 1: Sort by VENDOR: ");
System.out.println("Option 2: Sort decreasing number by MMAX: ");
System.out.println("Option 3: Sort decreasing number by CACH: ");
System.out.println("Option 4: Sort decreasing number by PRP: ");
System.out.println("Option 5: Quit program");
}
/**
* Constructor to handle the cases in the menu options
* #throws FileNotFoundException
* #throws IOException
*/
public Prog4() throws FileNotFoundException {
//Accepts user input
Scanner in = new Scanner(System.in);
//calls the menu method
menu();
//Initializes the run variable making the program loop until the user terminates the program
Boolean run = true;
//While loop
while (run) {
switch (in.nextInt()) {
case 1:
System.out.println("Option 1 selected");
System.out.println("Sorted by vendor:");
filename = new File("machine.txt");
//Instantiate Scanner s with f variable within parameters
//surround with try and catch to see whether the file was read or not
try {
input = new Scanner(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Instantiate a new Array of String type
String array [] = new String[10];
//while it has next ..
while (input.hasNext()) {
//Initialize variable
int i = 0;
//store each word read in array and use variable to move across array array[i] = input.next();
//print
System.out.println(array[i]);
//so we increment so we can store in the next array index
i++;
}
case 2:
System.out.println("Press any key to continue");
Scanner input2 = new Scanner(System.in);
String x = input2.nextLine();
if (x.equals(0)) continue;
System.out.println("Option 2 selected") ;
Computer[] c = new Computer[10];
filename = new File("machine.txt");
try {
input = new Scanner(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Arrays.sort(c);
while (input.hasNextLine()) {
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);
}
}
}
}
}
/**
* Main method
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
//Calls the constructor
new Prog4();
//static Scanner input;
}
public static void quickSort(int arr[], int left, int right) {
if (left < right) {
int q = partition(arr, left, right);
quickSort(arr, left, q);
quickSort(arr, q+1, right);
}
}
private static int partition(int arr[], int left, int right) {
int x = arr[left];
int i = left - 1;
int j = right + 1;
while (true) {
i++;
while (i < right && arr[i] < x)
i++;
j--;
while (j > left && arr[j] > x)
j--;
if (i < j)
swap(arr, i, j);
else
return j;
}
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Comparator class:
import java.util.Comparator;
class Computer implements Comparable<Computer> {
private String vendor;
private int mmax;
private int cach;
private int php;
public Computer(int value) {
this.mmax = value;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public int getMmax() {
return mmax;
}
public void setMmax(int mmax) {
this.mmax = mmax;
}
public int getCach() {
return cach;
}
public void setCach(int cach) {
this.cach = cach;
}
public int getPhp() {
return php;
}
public void setPhp(int php){
this.php = php;
}
#Override
public int compareTo(Computer m) {
if (mmax < m.mmax) {
return -1;
}
if (mmax > m.mmax) {
return 1;
}
// only sort by height if age is equal
if (cach > m.cach) {
return -1;
}
if (cach < m.cach) {
return 1;
}
if (php > m.php) {
return -1;
}
if (php < m.php) {
return 1;
}
return 0;
}
public static Comparator<Computer> ComparemMax = new Comparator<Computer>() {
#Override
public int compare(Computer p1, Computer p2) {
return p2.getMmax() - p1.getMmax();
}
};
}
The biggest problem is that the Computer classes do not get instantiated for each line that gets read.
As you want to have different sort options depending on the user input, you can not let the Computer class determine the compare method, but instead you will need to create a separate Comparator implementation for each sort option. Next, make the file read operation generic and abstract it away in a separate method call from each selected case. Instead of an array of Computers, I would make it a List or a Set, because you don't (want to) know the length up front.
I would like to lay out the steps in detail so that you could figure out each step for yourself. You have got a lot of it right.. but there are gaps.
Create a Computer class. It should have a constructor which takes a single String and splits it using the separator ',' and parses each part to String/int as applicable. (It would be preferable for you to parse and store the whole string.. which means you can have 10 fields in your class)
Create a blank ArrayList to store the Computer objects.
Iterate through the file and readLine
Call the Computer constructor using the String representing each line in the file within the while loop
Add the new Computer object to the computers ArrayList
Write 5 different comparators.
Based on user input, instantiate the correct comparator and pass it to the sort method
Print the sorted array
If you still face a problem, mention the specific point at which you like more clarity..
I've tried writing this code from scratch, coding, and running it but it just doesn't seem to work. This was assigned as lab work in class. The requirements are:
Implementing a postfix evaluation with the use of a stack and stack operations (user-defined).
I think the algorithm of my program is right, but it always gives me the wrong answer.
Here is my code.
public class StackApplication {
public static class Stack<T> {
private int top = 0;
private final static int stackMax=100;
// highest index of stk array
private Object[] stk = new Object[stackMax+1];
//Elements must be cast back.
public Stack() { // constructor
}
public boolean isEmpty(){
if (top==0) return true;
else return false;
}
public void push(T el) {
if(top==stackMax)
System.out.println("Stack push overflow error");
else top=top+1;
stk[top]=el;
}
public T pop(){
if(isEmpty()){
System.out.println("Stack push underflow error");
return null;
}
else top=top-1;
return(T)stk[top+1];
}
public T top(){
if(isEmpty()){
//System.out.println("Stack empty");
return null;
}
else return (T)stk[top];
}
}
public static boolean isOperator(char c){
return(c=='+' || c=='-' || c=='/' || c=='*' || c=='^');
}
public static double evaluate(double x, char o, double y) {
double result=0;
switch(o) {
case '+' : result=x+y; break;
case '-' : result=x-y; break;
case '*' : result=x*y; break;
case '/' : result=x/y; break;
case '^' : result=Math.pow(x, y); break;
default : break;
}
return result;
}
public static void main(String[] args) {
Scanner console=new Scanner(System.in);
Stack<Double> s=new Stack<Double>();
System.out.println("Input Postfix form to evaluate:");
String inp=console.nextLine();
char[] chararray=inp.toCharArray();
double b,a;
for(int i=0; i<chararray.length; i++) {
if(!isOperator(chararray[i]))
s.push((double)chararray[i]);
else {
b=s.pop();
a=s.pop();
double c=evaluate(a, chararray[i], b);
s.push(c);
}
}
System.out.println(" " +s.pop());
}
}
Sample Output:
Input Postfix form to evaluate:
23+ (Input)
101.0 (Output)
5.0 (Expected output)
The problem is here: s.push((double)chararray[i]);. You can't convert char to double this way. You are now taking the ascii code of 2 and 3.
50(ascii code of 2) + 51(ascii code of 3) = 101
Do it like this: s.push((double)(chararray[i] - '0'));
Your are doing the addition of the ASCII codes for 2 and 3, not of 2 and 3.
The code for 2 is 50 and for 3 is 51, so your out is 101, which is correct in this case.
When you push, push chararray[i]-'0'. This will solve your problem.