Splitting integers in Android - java

In relation to my last question about setting the TextView as the method output this question is about splitting the integer into separate digits. My Roman Numeral program works by using the translator method here:
'public static String translator(int integer) {
String result = "";
LinkedList<String> stack = new LinkedList<String>();
// if (integer > 0 && integer <= 4999) {
//ArrayList<Integer> placement = new ArrayList<Integer>();
int place = (int) Math.log10(integer);
for (int i = 0; i <= place; i++) {
//while(integer > 0){
//System.out.println(integer);
int placeOfValue = integer % 10;
//stack.push(placeOfValue);
//System.out.print(stack);
//System.out.print(placeOfValue +":" + i);
String placement = "";
switch (i) {
case 0:
placement = ones(placeOfValue);
break;
case 1:
placement = tens(placeOfValue);
break;
case 2:
placement = hundreds(placeOfValue);
break;
case 3:
placement = thousands(placeOfValue);
break;
default:
break;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
stack.push(placement);
}
integer = integer / 10;
//System.out.print(placement);
// System.out.println(placement.size());
//}
// for(int j = 0; j < placement.size(); j++){
// double tenthPower = Math.floor(Math.log10(placement.get(j)));
// double place = Math.pow(10, tenthPower);
// System.out.println(place);
//
// }
// }
while (!stack.isEmpty()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
result += stack.pop();
//System.out.print(stack.pop());
}
}
// } else {
// System.out.println("Please enter an integer between 0 and 4,999.");
// }
}
return result;
}
`
The translator method works by going through the for loop which will loop through the size of the integer then assigning the digit a given placement. From the placement it will then look through the placement methods and return the numeral. Since the integers are added in reverse for the LinkedList I have pushed the stack and popped it based on this post How to get the separate digits of an int number? to get the correct order. However the program continues to print out the numerals in reverse order which is not what I want. I have debugged the program but with no luck it feels like something is off with the pop method and adding it to the output but I can't figure out what.

I ended up solving this problem by uncommenting out a bracket which separated the stack.push() from the stack.pop(). After that the rest of the code works!

Related

Evaluating Polish Notation in Java with 2 stacks

I am writing an evaluation code for polish notation. When I overcome ClassCastException I get EmptyStack and when I solve Emptystack I get ClassCast I'm in a loop.
Here is how I wanted to evaluate the Polish notation:
First I get a string from the user then put it into a stack. For evaluating I use a second stack. Why?
Because:
An example string: "* + * + 1 2 + 3 4 5 6" First operation here is to add up 3 and 4 but what I'm gonna do with 5 and 6? I put them in another stack. Let's say stack2. I start popping until I found an operator, in this condition I pushed 6 5 4 3 into stack2 and found a plus operator. Then I pop 2 numbers which I pushed to stack2 (the top 2 numbers are 3 and 4), add them up, and push them to stack again.
I should evaluate but seems like I am missing a point or this wasn't a good idea at first.
Here is my code:
public class Main {
public static void stack(String srt){ // this function puts the string in srt stack
String arr[] = srt.split(" "); // I am recognizing if there is a 2 or more digit number
int size= arr.length; // with receiving prefix with " " btw every number and operator
Stack stack= new Stack();
for (String s : arr) {
// System.out.println(s);
stack.push(s);
}
// for (int i = 0; i < size; i++) {
// System.out.println(stack.pop()); // I checked to see if any
// problems first now I dont start this
// }
evaluate(stack); // then calls the evaluate function
}
public static void evaluate(Stack stack){
Stack stack2= new Stack();
stack2.push(stack.pop());// cuz of there cant be an operator there I pop first 2 number
stack2.push(stack.pop());
for (int i = 0; i < (stack.capacity()*2); i++) { // I had a hard time calculating how many times
// I should cycle through this for and leave it 2 times as stack capacity
if(stack.peek().toString().equals("*") || stack.peek().toString().equals("-") || stack.peek().toString().equals("/") || stack.peek().toString().equals("+")){
System.out.println("Checkpoint1");
// System.out.println(stack2.peek());
int s2= Integer.parseInt((String) stack2.pop());
int s1= Integer.parseInt((String) stack2.pop());
double s3;
String c = (String) stack.pop();
switch (c) {
case "+":
s3=s1+s2;
stack2.push(s3);
case "-":
s3=s1-s2;
stack2.push(s3);
case "*":
s3=s1*s2;
stack2.push(s3);
case "/":
s3=s1/s2;
stack2.push(s3);
}
}else{
System.out.println("Checkpoint 2");
stack2.push(Integer.parseInt((String) stack.pop()));
// System.out.println(stack.peek());
}
}
// System.out.println(stack.peek());
// System.out.println(stack2.peek());
}
public static void main(String[] args) {
String examplestr ="* + * + 1 2 + 3 4 5 6";
stack(examplestr);
}
}
Thank you for your help!!!
So turns out the switch-case doesn't operate correctly because I forgot a fundamental part "break". For EmptyStackException, I made a try-catch and put them inside so when it returns empty stack I know evaluation is done and print the result. BUT I still don't know how to deal with these little problems. It feels like I did not solve them properly. Gotta work more. Thanks.
Edit: I made some more adjustments and this is my final working code. I couldn't detect an error in the results yet.
Here is the working code;
import java.util.EmptyStackException;
import java.util.Stack;
public class Main2 {
public static void stack(String srt) {
String arr[] = srt.split(" ");
int size = arr.length;
Stack stack = new Stack();
for (int i = 0; i < size; i++) {
if (arr[i].toString().equals("*") || arr[i].toString().equals("-") || arr[i].toString().equals("/") || arr[i].toString().equals("+"))
stack.push(arr[i]);
else
stack.push(Double.parseDouble(arr[i]));
}
// for (int i = 0; i < size; i++) {
// System.out.println(stack.pop());
// }
evaluate(stack);
}
public static void evaluate(Stack stack) {
Stack stack1 = new Stack();
stack1.push(stack.pop());
stack1.push(stack.pop());
for (int i = 0; i < stack1.capacity(); i++) {
try {
if (stack.peek().toString().equals("*") || stack.peek().toString().equals("-") || stack.peek().toString().equals("/") || stack.peek().toString().equals("+")) {
// System.out.println("Checkpoint1");
double s1 = (double) stack1.pop();
double s2 = (double) stack1.pop();
double s3;
String operator = String.valueOf(stack.pop());
switch (operator) {
case "+":
s3 = s1 + s2;
stack1.push(s3);
break;
case "-":
s3 = s1 - s2;
stack1.push(s3);
break;
case "*":
s3 = s1 * s2;
stack1.push(s3);
break;
case "/":
s3 = s1 / s2;
stack1.push(s3);
break;
}
} else {
// System.out.println("Checkpoint 2");
stack1.push(Double.parseDouble(String.valueOf(stack.pop())));
}
} catch (EmptyStackException e) {
System.out.println("Notasyonun sonucu: " + stack1.peek());
}
}
}
public static void main(String[] args) {
String notasyon = scanner.nextLine();
stack(notasyon);
}
}

String Math Algorithm Gone Wrong JavaFX

As I was building my first JavaFX project, I noticed that the calculator engine that I had built was a little off. With that being said, I went over my code for about an hour now, trying to figure out what is wrong and I couldn't find anything that connects to this strange bug in my program.
The calculator engine:
public static String BasicEval(String str, String function) {
int indexOfOperation = str.indexOf(function);
int downBoundary = indexOfOperation - 1;
int upBoundary = indexOfOperation + 1;
int closestUp = str.length(), closestDown = 0;
for (int index = 0; index < str.length(); index++) { // Searching for the closest white space (between vals.) to determine what are the two vals.
if (Math.abs(indexOfOperation - index) == 1) {
continue;
} else if ((str.charAt(index) == ' ') && ((indexOfOperation - index) > closestDown)) {
closestDown = index; //Finds the closest blank space in order to differentiate between elements.
} else if ((str.charAt(index) == ' ') && (Math.abs(indexOfOperation + index) < closestUp)) {
closestUp = index; //Finds the closest black space in order to differentiate between elements.
}
}
while (str.substring(upBoundary,closestUp).contains("X") || (str.substring(upBoundary,closestUp).contains("-") || (str.substring(upBoundary,closestUp).contains("+") || (str.substring(upBoundary,closestUp).contains("/") || (str.substring(upBoundary,closestUp).contains("^")))))) {
closestUp--;
}
double firstValue = Double.valueOf(str.substring((closestDown + 1), downBoundary));
double secondValue = Double.valueOf(str.substring(upBoundary + 1, (closestUp-1)));
double OperationResult;
switch (function) {
case "^" : OperationResult = Math.pow(firstValue,secondValue); break;
case "X" : OperationResult = (firstValue * secondValue); break;
case "/" : OperationResult = (firstValue / secondValue); break;
case "+" : OperationResult = (firstValue + secondValue); break;
case "-" : OperationResult = firstValue - secondValue; break;
default: OperationResult = -999.12349876; //ERROR
}
str = strSort(str,firstValue,secondValue,OperationResult);
return str;
}
A little bit about the engine: the engine itself supposes to evaluate math expressions inside strings, so for example an input would be: " 3 + 4 " and the answer would be: 7.0 as a double. The way I hoped to achive this was by deviding the str into 4 smaller sections by the spaces between the terms and operation sign. The problem is: the math gets all wierd as you use bigger numbers. The number -999.123... stands for an error in my program.
The engine works just fine for simple calculations that use low numbers, but as you start to use bigger numbers things get messy. Sometimes it also produces errors like: "empty string", which I don't understand why ..
For more info about the project or the engine please comment.
-- Keep in mind that I'm looking for an answer that would apply to my algorithm, not to javaFX in general-- (though I'd love to learn new stuff)
Thanks !!
Examples of how things aren't as they should be:
enter image description here
enter image description here
I'll post more pictures in the comments.
strSort Method
public static String strSort(String str, double firstValue, double secondValue, double result) {
//Method that sorts between which vals are ints and which ones are doubles. --> returns them in their current form.
int firstValueIndex = 0;
int secondValueIndex = 0;
if (!intOrDoubleTest(firstValue) && firstValue == secondValue){ // Special category : indexOf doesn't work since the two vals. are the same --> giving off the same index.
firstValueIndex = str.indexOf(Double.toString(firstValue));
secondValueIndex = str.indexOf(Double.toString(secondValue),firstValueIndex+1);
} else if (intOrDoubleTest(firstValue) && firstValue == secondValue) { // Special category : indexOf doesn't work since the two vals. are the same --> giving off the same index.
firstValueIndex = str.indexOf(Integer.toString(intValue(firstValue)));
secondValueIndex = str.indexOf(Integer.toString(intValue(secondValue)),firstValueIndex+1);
} else if (intOrDoubleTest(firstValue) && intOrDoubleTest(secondValue)) { // First, sorts out the two vals.
firstValueIndex = str.indexOf(Integer.toString(intValue(firstValue)));
secondValueIndex = str.indexOf(Integer.toString(intValue(secondValue)));
} else if (!intOrDoubleTest(firstValue) && intOrDoubleTest(secondValue)) {
firstValueIndex = str.indexOf(Double.toString(firstValue));
secondValueIndex = str.indexOf(Integer.toString(intValue(secondValue)));
} else if (intOrDoubleTest(firstValue) && !intOrDoubleTest(secondValue)) {
firstValueIndex = str.indexOf(Integer.toString(intValue(firstValue)));
secondValueIndex = str.indexOf(Double.toString(secondValue));
} else if (!intOrDoubleTest(firstValue) && !intOrDoubleTest(secondValue)) {
firstValueIndex = str.indexOf(Double.toString(firstValue));
secondValueIndex = str.indexOf(Double.toString(secondValue));
}
String strToReplace = str.substring(firstValueIndex, secondValueIndex); // Computing the range that need to be replaced.
if (intOrDoubleTest(result)) {
int intResult = intValue(result);
str = str.replace(strToReplace,Integer.toString(intResult));
} else if (!intOrDoubleTest(result)) {
str = str.replace(strToReplace,Double.toString(result));
}
return str;
}
public static boolean intOrDoubleTest(double value) {
return (value % 1 == 0); // True = val is Int, False = val is Double.
}
Found the problem:
The problem was in the strToReplace.substring the strSort method. So naturally, I re-wrote the entire method in a much simpler, nicer way.
public static String strSort(String str, double firstValue, double secondValue, double result) {
//Method that sorts between which vals are ints and which ones are doubles. --> returns them in their current form.
int firstValueIndex;
int secondValueIndex;
if (intOrDoubleTest(firstValue)) {
firstValueIndex = str.indexOf(Integer.toString(intValue(firstValue)));
} else {
firstValueIndex = str.indexOf(Double.toString(firstValue));
}
if (intOrDoubleTest(secondValue)) {
secondValueIndex = str.indexOf(Integer.toString(intValue(secondValue)), firstValueIndex+1);
} else {
secondValueIndex = str.indexOf(Double.toString(secondValue), firstValueIndex+1);
}
int lengthOfSecondVal;
lengthOfSecondVal = (int)(Math.log10(secondValue)+1);
String strToReplace = str.substring(firstValueIndex, secondValueIndex+lengthOfSecondVal); // Computing the range that need to be replaced.
if (intOrDoubleTest(result)) {
int intResult = intValue(result);
str = str.replace(strToReplace,Integer.toString(intResult));
} else if (!intOrDoubleTest(result)) {
str = str.replace(strToReplace,Double.toString(result));
}
return str;
}
public static boolean intOrDoubleTest(double value) {
return (value % 1 == 0); // True = val is Int, False = val is Double.
}
Thank you to all of you that helped !!

how can I check if a string is a floating point number?

In my program I'm going to store user input in an array then going to check each character to see if it's a digit or dot or E or negative sign after that I'll store it in to an array called temps.
Now I have problem in my fleating method () that don't how should I make my condition for the pattern of floating number digit-digit-dot-digit-digit (e.g 12.22)
I have my work here:
public void sorting(String data) {
String[] temps = new String[200];
int cpos = 0;
int tpos = 0;
Arrays.fill(temps, null);
if (str.isEmpty() == false) {
char char1 = str.charAt(cpos);
int i = 0;
while (i < str.length()) {
char1 = str.charAt(cpos);
char1 = str.charAt(tpos);
System.out.println("the current value is " + char1 + " ");
tpos++;
if (Character.isDigit(char1)) {
temps[cpos] = "Digit";
// System.out.println(" this number is digit");
cpos++;
} else if (char1 == 'e' || char1 == 'E') {
temps[cpos] = "s_notaion";
cpos++;
} else if (char1 == '-') {
temps[cpos] = "negative";
cpos++;
} else if (char1 == '.') {
temps[cpos] = ".";
cpos++;
}
i++;
}
}
}
here is the method for floating number
private static boolean floating(String [] data) {
int count =0;
boolean correct = false;
for (int i = 0; i < data.length; i++) {
if (data[i]== "Digit" )
&& data[i]=="." && data[i]"Digit"){
// here is the problem for the condition
}
}
return false;
}
If I understood correctly, the Data array has stuff like ["Digit","Digit",".","Digit"]
So you want the
private static boolean floating(String [] data) {
method to return true if the array only has "Digit" entries and exactly one "." entry? is that it?
If so:
boolean foundLeDigit = false;
for (int i = 0; i < data.length; i++) {
if (data[i].equals("Digit") == false && data[i].equals(".") == false {
//we found something other than a Digit or . it's not a float
return false;
}
if(data[i].equals(".")) {
if(foundLeDigit) { return false; //as we found 2 "." }
foundLeDigit = true
}
}
return foundLeDigit;
The easiest way to test if a String can represent a float is to try to parse it:
String testString = "1.2345";
double result;
try {
result = Double.parseDouble(testString);
System.out.println("Success!")
}
catch (NumberFormatException nfe) {
// wasn't a double, deal with the failure in whatever way you like
}
The questions lacks a bit of context, so for my answer I'm going to presume that this is homework requiring a manual solution, and that all floating point numbers are supposed to be accepted.
Your approach (while over-engineered) is half-right: you are reducing the input string into classes of characters - digit, sign, exponent marker. What is missing is that now you have to make sure that these character classes come in the right order.
Identify the various parts of float numbers (just look at 0, -1.0, 400E30, 42.1E-30) and you'll see that they come in a specific order, even if some are optional, and that each part imposes restrictions on what characters are allowed there. For example, if there is an 'E' in the number, it has to be followed by a number (with optional sign).
So as you step through the characters of the string, think about how you could keep track of where you are in the number, and base your character validation on that (this is the state machine #JonKiparsky was mentioning).
A few small things:
Don't compare strings with '==' - use equalsTo().
Think about what it means if sorting() finds a character which is neither a digit, a sign, or the exponent 'E'?
You allocate the temps array for 200 entries, but the input string could be larger.
using the regular expression is the best way to Handel this problem
private static boolean floating(String [] data) {
int count =0;
boolean correct = false;
for (int i = 0; i < data.length; i++) {
if (str.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")){
System.out.println(" it's a floating number ");
correct= true;
break;
}else
correct = false;
}if (correct ==true){
return true;
}else
return false;
}

Applying Linear and Binary Searches to Arrays

I have to create a program that takes a user input (a number) and then the program should have that number and apply a search to the array and output the corresponding title by matching the index and the number the user inputted. However during run time, nothing happens. I have set breakers in my code and noticed a problem with the for loop (search algorithm). Please help me and let me know what is wrong is my search algorithm. What I am trying to do is use the number of that the user inputs to match a index and then output the book title that is stored in the index.
private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// declares an array
String[] listOfBooks = new String [101];
// assigns index in array to book title
listOfBooks[1] = "The Adventures of Tom Sawyer";
listOfBooks[2] = "Huckleberry Finn";
listOfBooks[4] = "The Sword in the Stone";
listOfBooks[6] = "Stuart Little";
listOfBooks[10] = "Treasure Island";
listOfBooks[12] = "Test";
listOfBooks[14] = "Alice's Adventures in Wonderland";
listOfBooks[20] = "Twenty Thousand Leagues Under the Sea";
listOfBooks[24] = "Peter Pan";
listOfBooks[26] = "Charlotte's Web";
listOfBooks[31] = "A Little Princess";
listOfBooks[32] = "Little Women";
listOfBooks[33] = "Black Beauty";
listOfBooks[35] = "The Merry Adventures of Robin Hood";
listOfBooks[40] = "Robinson Crusoe";
listOfBooks[46] = "Anne of Green Gables";
listOfBooks[50] = "Little House in the Big Woods";
listOfBooks[52] = "Swiss Family Robinson";
listOfBooks[54] = "The Lion, the Witch and the Wardrobe";
listOfBooks[54] = "Heidi";
listOfBooks[66] = "A Winkle in Time";
listOfBooks[100] = "Mary Poppins";
// gets user input
String numberInput = txtNumberInput.getText();
int number = Integer.parseInt(numberInput);
// Linear search to match index number and user input number
for(int i = 0; i < listOfBooks.length - 1; i++) {
if (listOfBooks.get(i) == number) {
txtLinearOutput.setText(listOfBooks[i]);
break;
}
}
*There is a problem with the listOfBooks.get in the if statement. Also I need to apply a binary search that would search the same array just using the binary method. Need help to apply this type of binary search.
How could I make a statement that checks if the int number is equal to an index?
Note that the following code is just an example of what I have to apply. Variables are all for example purposes:
public static Boolean binarySearch(String [ ] A, int left, int right, String V){
int middle;
if (left > right) {
return false;
}
middle = (left + right)/2;
int compare = V.compareTo(A[middle]);
if (compare == 0) {
return true;
}
if (compare < 0) {
return binarySearch(A, left, middle-1, V);
} else {
return binarySearch(A, middle + 1, right, V);
}
}
you can avoid for loop and check condition by just giving number like this: txtLinearOutput.setText(listOfBooks[number-1]);
remove your code
// Linear search to match index number and user input number
for(int i = 0; i < listOfBooks.length - 1; i++) {
if (listOfBooks.get(i) == number) {
txtLinearOutput.setText(listOfBooks[i]);
break;
}
with
try{
int number = Integer.parseInt(numberInput);
if(number>0 && number<101){
txtLinearOutput.setText(listOfBooks[number-1]);
}else{
// out of range
}
}catch(Exception e){
// handle exception here
}
You are comparing if (listOfBooks.get(i) == number) it is wrong, you should compare: if (i == number), becouse you need compare element position.
This isn't a binary search answer. Just an implementation of HashMap. Have a look at it.
HashMap<String, Integer> books = new HashMap();
books.put("abc", 1);
books.put("xyz", 2);
books.put("pqr", 3);
books.put("lmo", 4);
System.out.println(books.getValue("abc");
Using the inbuilt BinarySearch.
String []arr = new String[15];
arr[0] = "abc";
arr[5] = "prq";
arr[7] = "lmo";
arr[10] = "xyz";
System.out.println(Arrays.binarySearch(arr, "lmo"));
How to compare Strings using binary search.
String[] array = new String[4];
array[0] = "abc";
array[1] = "lmo";
array[2] = "pqr";
array[3] = "xyz";
int first, last, middle;
first = 0;
last = array.length - 1;
middle = (first + last) / 2;
String key = "abc";
while (first <= last) {
if (compare(array[middle], key))
first = middle + 1;
else if (array[middle].equals(key)) {
System.out.println(key + " found at location " + (middle) + ".");
break;
} else {
last = middle - 1;
}
middle = (first + last) / 2;
}
if (first > last)
System.out.println(key + " is not found.\n");
}
private static boolean compare(String string, String key) {
// TODO Auto-generated method stub
for (int i = 0; i < Math.min(string.length(), key.length()); ++i)
if (string.charAt(i) < key.charAt(i))
return true;
return false;
}
Your linear search code looks something like this
try{
txtLinearOutput.setText(listOfBooks[yourNumber]);
}
catch(IndexOutOfBoundsException ie){
// prompt that number is not an index
}
catch(Exception e){
// if any other exception is caught
}
What you are doing here:
if (listOfBooks.get(i) == number) {
is that you are matching the content of the array with the input number, which is irrelevant.
You can directly use the input number to fetch the value stored at the index.
For example:
txtLinearOutput.setText(listOfBooks[number-1]);
Additionally, int number = Integer.parseInt(numberInput); should be placed within try-catch block to validate input number parsing. And you can check if the input number is within the range of the array to avoid exceptions like:
try{
int number = Integer.parseInt(numberInput);
// Linear search to match index number and user input number
if (number > 0 && number <=100) {
txtLinearOutput.setText(listOfBooks[number-1]);
} else {
// Display error message
}
} catch(Exception e) {
// Handle exception and display error message
}
And for using binary search, the string array need to be sorted. You can use Arrays.sort() method for sorting it.
And regarding using binary search, you can use Java Arrays Binary Search method

Stack problem java. Postfix Evaluation

Hey Guys I'm having a problem when I run my program. In the PostfixEvaluate() Method is where it takes in a string and solves the postfix problem and returns it. Well when I go to run it, I'm getting a bunch of random numbers(some repeated), I'm going crazy because I don't know what else to try and I've spent more time on this than it should normally take.
Heres the PostfixEvaluate Method:
public int PostfixEvaluate(String e){
//String Operator = "";
int number1;
int number2;
int result=0;
char c;
//number1 = 0;
//number2 = 0;
for(int j = 0; j < e.length(); j++){
c = e.charAt(j);
if (c != '+'&& c!= '*' && c!= '-' && c!= '/') {
//if (c == Integer.parseInt(e)) {
s.push(c);
}
else {
number1 = s.pop();
number2 = s.pop();
switch(c) {
case '+':
result = number1 + number2;
break;
case '-':
result = number1 - number2;
break;
case '*':
result = number1 * number2;
break;
case '/':
result = number1 / number2;
break;
} s.push(result);
}
System.out.println(result);
}
return s.pop();
}
public static void main(String[] args) {
Stacked st = new Stacked(100);
String y = new String("(z * j)/(b * 8) ^2");
String x = new String("2 3 + 9 *");
TestingClass clas = new TestingClass(st);
clas.test(y);
clas.PostfixEvaluate(x);
}
}
This is the Stack Class:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = -1;
maxLen = max;
stack = new char[maxLen];
}
public void push(int result) {
top++;
stack[top] = (char)result;
}
public int pop() {
int x;
x = stack[top];
//top = top - 1;
top--;
return x;
}
public boolean isStackEmpty() {
if(top == -1) {
System.out.println("Stack is empty " + "Equation Good");
return true;
}
else
System.out.println("Equation is No good");
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j = top; j > -1; j--){
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j=0; j>=top; j++){
System.out.println(stack[j]);
}
System.out.println(" ");
}
}
It looks to me like you aren't handling spaces at all.
This means that when you put in a space, it is implicitly converting the character space to the ascii value of it (32) when it pops it off the stack during an operation. Also, it looks like you are assuming that all numbers/results will be single digit, and casting from char to int, which is not what you want to do, since that will convert the char to the ascii value of the char, ' ' -> 32, '3' -> 51, etc.
If I were you, I would do this for your loop in PostfixEvaluate:
while(!e.equals("")){
string c;
int space = e.indexOf(' ');
if(space!=-1){
c = e.substring(0,space);
e = e.substring(space+2);
} else{
c = e;
e = "";
}
if (!c.equals("+")&& !c.equal("*") && !c.equals("-") && !c.equals("/")) {
//...
}
and change your stack to hold strings or ints.
The problem is that you are pushing char onto a stack as an int, so you are unintentionally working with the ascii representations of numbers, which is not the actual value of the number.
Instead of this complicated character walking, tokenize the input string using String.split(). Example:
String[] tokens = e.split(" ");
for(String token:tokens){
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
s.push(Integer.parseInt(token));
} else {
....
}
}
You need to split the string into tokens first:
/* Splits the expression up into several Strings,
* all of which are either a number or and operator,
* none of which have spaces in them. */
String [] expressionAsTokens = e.split(" ");
Then you need to make sure you compare Strings, not chars:
//compare strings instead of chars
String token = expressionAsTokens[j];
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
s.push(Integer.parseInt(token));
} else {
//same code as you had before
}
Also, is there any reason you are storing everything as a char array in your Stacked class? Your pop() method returns and integer, yet everything is stored as a char.
For this application, everything should be stored as an integer:
public class Stacked {
int stack[]; // array is of type integer
int top;
int maxLen;
// constructor
public void push() {/*...*/}
public int pop() {/*...*/} //pop returns an int as before
//...
}
One final note: Be careful what order you add and subtract the numbers in. I don't remember if postfix operands are evaluated left first or right first, but make sure you get them in the right order. As you have it now, 2 3 - 4 * would evaluate as 4 * (3 - 2) and I think it should be (2 - 3) * 4. This won't matter with adding and multiplying, but it will with subtracting and dividing.

Categories