Why am I getting an empty stack exception? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Please help in this regard, the error is shown as empty stack exception.
Code:
import java.util.Stack;
public class Stacks {
public static void main(String[] arg)
{
String s[] = {"5 + ) * ( 2",
// " 2 + ( - 3 * 5 ) ",
"(( 2 + 3 ) * 5 ) * 8 ",
"5 * 10 + ( 15 - 20 ) ) - 25",
" 5 + ( 5 * 10 + ( 15 - 20 ) - 25 ) * 9"
};
for (int i = 0; i < s.length; i++)
{
Arithmetic a = new Arithmetic(s[i]);
if (a.isBalance())
{
System.out.println("Expression " + s[i] + " is balanced\n");
a.postfixExpression();
System.out.println("The post fixed expression is " + a.getPostfix());
a.evaluateRPN();
}
else
System.out.println("Expression is not balanced\n");
}
}
private static class Arithmetic {
String str = "";
Stack<Character> stack = new Stack<>();
String postFix = "";
public Arithmetic(String str)
{
this.str = str;
this.postFix = postFix;
}
private boolean isBalance()
{
Stack<Character> stack = new Stack<>();
for(int i = 0; i < str.length(); i++)
{
if(str.charAt(i) == '(' )
stack.push(str.charAt(i));
else if(str.charAt(i) == ')')
{
if(stack.isEmpty() || stack.pop() != '(')
return false;
}
}
return stack.isEmpty();
}
private void evaluateRPN() {
}
private String getPostfix() {
return postFix;
}
#SuppressWarnings("empty-statement")
private void postfixExpression() {
Stack<Character> stack = new Stack<>();
for(int i = 0; i < str.length(); i++)
{
if(Character.isDigit(str.charAt(i)))
postFix += " " + str.charAt(i);
else if(str.charAt(i) == '+' || str.charAt(i) == '-' ||
str.charAt(i) == '*' || str.charAt(i) == '/' ||
str.charAt(i) == '%' || str.charAt(i) == '(' ||
str.charAt(i) == ')' )
{
do{
stack.push(str.charAt(i));
}
while(stack.isEmpty());
}
if(str.charAt(i) == '(' || str.charAt(i) == ')')
{
if(str.charAt(i) == '(')
stack.push(str.charAt(i));
else if(str.charAt(i) == ')')
{
do
{
do{
postFix += stack.pop();
}while(stack.pop() != ')');
}while(!stack.empty());
}
}
if(str.charAt(i) == '+' || str.charAt(i) == '-' ||
str.charAt(i) == '*' || str.charAt(i) == '/' )
{
if(str.charAt(i) == '+' || str.charAt(i) == '-')
{
do{
postFix += stack.pop();
}while ((stack.pop() != '(') || !stack.empty());
postFix += str.charAt(i);
}
if(str.charAt(i) == '*' || str.charAt(i) == '/')
{
if(stack.pop() == '+' || stack.pop() == '-')
{
stack.push(str.charAt(i));
}
}
}
}
do{
postFix += stack.pop();
}while(!stack.empty());
}
}
}

When you testing use peek function otherwise you are removing the item. When you do :
if(stack.pop() == '+' || stack.pop() == '-')
and your stack contains [*]
When you call stack.pop() you remove * and your stack will be empty after that and you will get exception in second test (stack.pop() == '-').
You need to verify your code and change your logic.

Related

Leetcode Proble - 20. Valid Parentheses

I am trying to solve this leetcode problem:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
I think I am almost correct and have been working on this problem for a long time but couldn't get the correct output especially a case where input is "())".
class Solution {
public boolean isValid(String s) {
Stack<Character> c = new Stack<>();
int n = s.length();
boolean bool = false;
if (s.isEmpty() | s == null) { // Correct
return true;
}
for (int i=0 ; i<n ; i++) {
if (s.charAt(i) == '{') {
c.push('{');
} else if (s.charAt(i) == '[') {
c.push('[');
} else if (s.charAt(i) == '(') {
c.push('(');
} else if (s.charAt(i) == '}' & c.peek() == '{') {
c.pop();
} else if (s.charAt(i) == ']' & c.peek() == '[') {
c.pop();
} else if (s.charAt(i) == ')' & c.peek() == '(') {
c.pop();
} else {
break;
}
}
if (c.isEmpty()) {
return true;
} else {
return false;
}
}
}
I think you should check stack's size before process these conditions.
else if (s.charAt(i) == '}' & c.peek() == '{') {
c.pop();
} else if (s.charAt(i) == ']' & c.peek() == '[') {
c.pop();
} else if (s.charAt(i) == ')' & c.peek() == '(') {
c.pop();
}
The problem is that you are not adding the closure brackets to the stack, so your check of the stack size at the end returns false results.
You could change your ifs to already return false when a open bracket is missing i.e.
else if (s.charAt(i) == '}') {
if(c.peek() == '{'){
c.pop();
}
else{
return false;
}
}
The others would need to be changed similarly.
Thank you all for your suggestions.
I figured out that I should check whether the stack is empty or not before using peek().
else if (s.charAt(i) == '}') {
if (!c.isEmpty() && c.peek() == '{') {
c.pop();
}
else {
return false;
}
In case someone is looking for the javascript solution.
var isValid = function (s) {
// Stack to store left symbols
const leftSymbols = [];
// Loop for each character of the string
for (let i = 0; i < s.length; i++) {
// If left symbol is encountered
if (s[i] === '(' || s[i] === '{' || s[i] === '[') {
leftSymbols.push(s[i]);
}
// If right symbol is encountered
else if (s[i] === ')' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '(') {
leftSymbols.pop();
} else if (s[i] === '}' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '{') {
leftSymbols.pop();
} else if (s[i] === ']' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '[') {
leftSymbols.pop();
}
// If none of the valid symbols is encountered
else {
return false;
}
}
return leftSymbols.length === 0;
};
Try this once->
var isValid = function (s = "{[]}") {
const leftSymbols = [];
for (let i = 0; i < s.length; i++) {
if (s[i] === "(" || s[i] === "{" || s[i] === "[") {
leftSymbols.push(s[i]);
} else if (
s[i] === ")" &&
leftSymbols.length !== 0 &&
leftSymbols[leftSymbols.length - 1] === "("
) {
leftSymbols.pop();
} else if (
s[i] === "}" &&
leftSymbols.length !== 0 &&
leftSymbols[leftSymbols.length - 1] === "{"
) {
leftSymbols.pop();
} else if (
s[i] === "]" &&
leftSymbols.length !== 0 &&
leftSymbols[leftSymbols.length - 1] === "["
) {
leftSymbols.pop();
} else {
return false;
}
}
return leftSymbols.length === 0;
};
console.log(isValid());
In case someone is looking for the java solution:
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i=0; i<s.length(); i++){
char strChar = s.charAt(i);
if(stack.empty()){
stack.push(strChar);
} else{
char stkChar = (char) stack.peek();
if(stkChar == '(' && strChar ==')' ){
stack.pop();
} else if(stkChar == '{' && strChar=='}'){
stack.pop();
} else if(stkChar == '[' && strChar == ']'){
stack.pop();
} else{
stack.push(strChar);
}
}
}
return (stack.empty() ? "true" : "false");
}

Java - Irregular spaces in postfix expression

My program works fine, but I'm getting some irregular spaces in the output. For example, if the input is 44 * 5 + 6 the output is 44<2 spaces>5<1 space>*<1space>6<no space>+. I tried fiddling with all the lines of code that are adding to the String postfix, but to no avail. I'd like the output to be of the form: operand<1 space>operand<1 space>operator (i.e. 1 space between operands and operators."
Here's my code:
import java.util.*;
public class PostfixConversion {
public static void main(String args[]) {
System.out.print("Enter an expression: ");
String infix = new Scanner(System.in).nextLine();
String postfix = convertToPostfix(infix);
System.out.println(postfix);
//System.out.println("The result of calculation is: " + postfixEvaluate("23+"));
}
//converts infix expression into postfix expression
public static String convertToPostfix(String infixExp) {
String postFix = "The Postfix Expression is: ";
Stack<Character> stack = new Stack<Character>();
char character = ' ';
for(int i = 0; i < infixExp.length(); i++)
{
character = infixExp.charAt(i);
//determine if character is an operator
if(character == '*' || character == '-' || character == '/' || character == '+')
{
//postFix += " ";
while(!stack.empty() && precedence(stack.peek(), character))
postFix += stack.pop();
stack.push(character);
} else if(character == '(') {
stack.push(character);
} else if(character == ')') {
while(!stack.peek().equals('(') && !stack.isEmpty())
postFix += stack.pop();
if(!stack.isEmpty() && stack.peek().equals('('))
stack.pop(); // pop/remove left parenthesis
} else
postFix += character;
}
while(!stack.empty()) //add the remaining elements of stack to postfix expression
{
if(stack.peek().equals('('))
{
postFix = "There is no matching right parenthesis.";
return postFix;
}
postFix += stack.pop();
}
return postFix;
}
public static boolean precedence(char first, char second) {
int v1 = 0, v2 = 0;
//find value for first operator
if(first == '-' || first == '+')
v1 = 1;
else if(first == '*' || first == '/')
v1 = 2;
//find value for second operator
if(second == '-' || second == '+')
v2 = 1;
else if(second == '*' || second == '/')
v2 = 2;
if(v1 < v2)
return false;
return true;
}
First remove all whitespaces from input, so that they don't destroy your formatting:infixExp = infixExp.replaceAll("\\s",""); and then add whitespaces where needed.

Phone numbers in java

I've got the code to put a seven letter phrase into a phone number. The hyphen is not returning in the correct spot. I really don't know how to fix this problem. It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem!
Code:
import java.util.*;
import java.lang.*;
public class Project1 {
public static char getNumber(char letter) {
char ret = 0;
if (letter== 'A' || letter=='a' || letter== 'B' || letter=='b' || letter=='C' || letter=='c') {
return '2';
}
else if (letter== 'D' || letter=='d' || letter== 'E' || letter=='e' || letter=='F' || letter=='f') {
return '3';
}
else if (letter== 'G' || letter=='g' || letter== 'H' || letter=='h' || letter=='I' || letter=='i') {
return '4';
}
else if (letter== 'J' || letter=='j' || letter== 'K' || letter=='k' || letter=='L' || letter=='l') {
return '5';
}
else if (letter== 'M' || letter=='m' || letter== 'N' || letter=='n' || letter=='O' || letter=='o') {
return '6';
}
else if (letter== 'P' || letter=='p' || letter== 'Q' || letter=='q' || letter=='R' || letter=='r'|| letter=='S' || letter=='s') {
return '7';
}
else if (letter== 'T' || letter=='t' || letter== 'U' || letter=='u' || letter=='V' || letter=='v') {
return '8';
}
else if (letter== 'W' || letter=='w' || letter== 'X' || letter=='x' || letter=='Y' || letter=='y' || letter=='Z' || letter=='z') {
return '9';
}
if (letter == ' ')
return '-';
return ret;
}
public static void main (String[] arg) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a 7 letter phrase: ");
String number = input.nextLine();
for (int i = 0; i < 8; i++) {
System.out.print(getNumber(number.toUpperCase().charAt(i)));
}
}
}
It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem!
Here you go! A bit of regex is always good for the soul:
{
String number = input.nextLine();
final StringBuilder builder = new StringBuilder(); // Buffer the sequence.
for (int i = 0; i < 8; i++) {
builder.append(getNumber(number.toUpperCase().charAt(i)));
if (builder.toString().getCharAt(2) != '-') // If the format isn't correct, fix it
System.out.println(builder.toString().replaceFirst("(...)(.).(...)", "$1-$2$3"))
}
}
As seen from CSáµ 's comment, you can use the following universal regex instead, such that the section becomes:
builder.toString().replaceFirst("^\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*$", "$1$2$3-$4$5$6$7");
Edit: Updated regex as \N backreferences does not work in Java.
Here's a quick and dirty solution to your problem.
import java.util.*;
public class Project1 {
public static char getNumber(char letter) {
char ret = 0;
if( letter < 'A' )
{
ret = '0';
}
else if( letter < 'D' )
{
ret = '2';
}
else if( letter < 'G' )
{
ret = '3';
}
else if( letter < 'J' )
{
ret = '4';
}
else if( letter < 'M' )
{
ret = '5';
}
else if( letter < 'P' )
{
ret = '6';
}
else if( letter < 'T' )
{
ret = '7';
}
else if( letter < 'W' )
{
ret = '8';
}
else if( letter <= 'Z' )
{
ret = '9';
}
else
{
ret = '0';
}
return ret;
}
public static void main (String[] arg) {
Scanner input = new Scanner(System.in);
System.out.println( "Please enter a 7 letter phrase: " );
String number = input.nextLine().toUpperCase();
StringBuffer buff = new StringBuffer();
for( int i = 0, j = 0; j < number.length() && i < 7; j++ )
{
char c = number.charAt(j);
if( c != ' ' )
{
if( i == 3 )
{
buff.append( '-' );
}
buff.append( getNumber( c ) );
i++;
}
}
System.out.println( buff );
}
}
Key points:
There is no need to check for lower case if the alpha characters are guaranteed to be uppercase.
There is no need to uppercase the input string on each iteration of the loop. Do it once at the beginning.
I'm ignoring spaces, and always adding a hyphen before I print position 3 (ie the fourth character).
chars can be compared just like numbers, using ranges. This simplifies the amount of code quite a bit (ie. each letter within a range doesn't need to be written down).

How to remove spaces from blackberry URL [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Blackberry URL encoder
i am using
String url="http://xxxxxx.com/api/api.php?func=xxxxxxxxxxxx&params[]="+searchText+CustomUtility.getConnectionString();
HttpConnection conn=(HttpConnection)Connector.open(url);
InputStream in=(InputStream)conn.openInputStream();
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
parser.parse(in, new ContactParser());
problem is this when searchText has many spaces it is not working , so please how i can remove spaces from URL
try this -
URLUTF8Encoder.enceode(searchText);
URLUTF8Encoder class is given below-
public class URLUTF8Encoder {
final static String[] hex = {
"%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07",
"%08", "%09", "%0A", "%0B", "%0C", "%0D", "%0E", "%0F",
"%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17",
"%18", "%19", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F",
"%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27",
"%28", "%29", "%2A", "%2B", "%2C", "%2D", "%2E", "%2F",
"%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37",
"%38", "%39", "%3A", "%3B", "%3C", "%3D", "%3E", "%3F",
"%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47",
"%48", "%49", "%4A", "%4B", "%4C", "%4D", "%4E", "%4F",
"%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57",
"%58", "%59", "%5A", "%5B", "%5C", "%5D", "%5E", "%5F",
"%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67",
"%68", "%69", "%6A", "%6B", "%6C", "%6D", "%6E", "%6F",
"%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77",
"%78", "%79", "%7A", "%7B", "%7C", "%7D", "%7E", "%7F",
"%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87",
"%88", "%89", "%8A", "%8B", "%8C", "%8D", "%8E", "%8F",
"%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97",
"%98", "%99", "%9A", "%9B", "%9C", "%9D", "%9E", "%9F",
"%A0", "%A1", "%A2", "%A3", "%A4", "%A5", "%A6", "%A7",
"%A8", "%A9", "%AA", "%AB", "%AC", "%AD", "%AE", "%AF",
"%B0", "%B1", "%B2", "%B3", "%B4", "%B5", "%B6", "%B7",
"%B8", "%B9", "%BA", "%BB", "%BC", "%BD", "%BE", "%BF",
"%C0", "%C1", "%C2", "%C3", "%C4", "%C5", "%C6", "%C7",
"%C8", "%C9", "%CA", "%CB", "%CC", "%CD", "%CE", "%CF",
"%D0", "%D1", "%D2", "%D3", "%D4", "%D5", "%D6", "%D7",
"%D8", "%D9", "%DA", "%DB", "%DC", "%DD", "%DE", "%DF",
"%E0", "%E1", "%E2", "%E3", "%E4", "%E5", "%E6", "%E7",
"%E8", "%E9", "%EA", "%EB", "%EC", "%ED", "%EE", "%EF",
"%F0", "%F1", "%F2", "%F3", "%F4", "%F5", "%F6", "%F7",
"%F8", "%F9", "%FA", "%FB", "%FC", "%FD", "%FE", "%FF"
};
public static String encode(String s)
{
StringBuffer sbuf = new StringBuffer();
int len = s.length();
for (int i = 0; i < len; i++) {
int ch = s.charAt(i);
if ('A' <= ch && ch <= 'Z') { // 'A'..'Z'
sbuf.append((char)ch);
} else if ('a' <= ch && ch <= 'z') { // 'a'..'z'
sbuf.append((char)ch);
} else if ('0' <= ch && ch <= '9') { // '0'..'9'
sbuf.append((char)ch);
} else if (ch == ' ') { // space
//sbuf.append('+');
sbuf.append("%20");
} else if (ch == '!') {
sbuf.append("%21");
} else if (ch == '*') {
sbuf.append("%2A");
} else if (ch == '(') {
sbuf.append("%28");
} else if (ch == ')') {
sbuf.append("%29");
} else if (ch == '\'') {
sbuf.append("%27");
} else if (ch == '-' || ch == '_' // unreserved
|| ch == '.'
|| ch == '~' || ch == '\'') {
sbuf.append((char)ch);
} else if (ch <= 0x007f) { // other ASCII
sbuf.append(hex[ch]);
} else if (ch <= 0x07FF) { // non-ASCII <= 0x7FF
sbuf.append(hex[0xc0 | (ch >> 6)]);
sbuf.append(hex[0x80 | (ch & 0x3F)]);
} else { // 0x7FF < ch <= 0xFFFF
sbuf.append(hex[0xe0 | (ch >> 12)]);
sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
sbuf.append(hex[0x80 | (ch & 0x3F)]);
}
}
return sbuf.toString();
}
}
you can use the below code to remove white space character in a given string ,you can call this method like this:
replace("PassyourString" , " " , "");
public static String replace(String s, String f, String r) {
if (s == null) {
return s;
}
if (f == null) {
return s;
}
if (r == null) {
r = "";
}
int index01 = s.indexOf(f);
while (index01 != -1) {
s = s.substring(0, index01) + r + s.substring(index01 + f.length());
index01 += r.length();
index01 = s.indexOf(f, index01);
}
return s;
}

infix to postfix program not working [duplicate]

This question already has answers here:
Handling parenthesis while converting infix expressions to postfix expressions
(2 answers)
Closed 6 years ago.
I am supposed to write a program to convert infix to postfix. It works for some, but other times not correctly. Especially on infix expressions containing parantheses. Could anyone give me a clue why this is wrong? For example, the infix expression
( ( 5 + 5 * ( 6 - 2 ) + 4 ^ 2 ) * 8 )
returns 5562-*42^++8*((2.
import java.io.*;
import java.util.Scanner;
public class InfixToPostfix
{
//class attributes
private char curValue;
private String postfix;
private LineWriter lw;
private ObjectStack os;
//constructor
public InfixToPostfix(LineWriter l, ObjectStack o)
{
curValue = ' ';
lw=l;
os=o;
}
public String conversion(String buf)
{
String temp =" ";
StringBuffer postfixStrBuf= new StringBuffer(temp);
char popped= new Character(' ');
char topped=' ';
for (int i=0; i<buf.length(); i++)
{
curValue= buf.charAt(i);
if (curValue == '(')
os.push(curValue);
if (curValue == ')')
{
while (popped != '(')
{
popped = ((Character)os.pop());
if (popped != '(')
postfixStrBuf.append(popped);
}
}
if (isOperator(curValue))
{
if( os.isEmpty())
os.push((Character)(curValue));
else
topped=((Character)os.top());
if ( (priority(topped)) >= (priority(curValue)) && (topped != ' ') )
{
popped = ((Character)os.pop());
if (popped != '(')
postfixStrBuf.append(popped);
//if it is a left paranthess, we want to go ahead and push it anyways
os.push((Character)(curValue));
}
if ( (priority(topped)) < (priority(curValue)) && (topped != ' ') )
os.push((Character)(curValue));
}
else if (!isOperator(curValue) && (curValue != ' ') && (curValue != '(' ) && (curValue != ')' ))
postfixStrBuf.append(curValue);
}
//before you grab the next line of the file , pop off whatever is remaining off the stack and append it to
//the infix expression
getRemainingOp(postfixStrBuf);
return postfix;
//postfixStrBuf.delete(0, postfixStrBuf.length());
}
public int priority(char curValue)
{
switch (curValue)
{
case '^': return 3;
case '*':
case '/': return 2;
case '+':
case '-': return 1;
default : return 0;
}
}
public boolean isOperator(char curValue)
{
boolean operator = false;
if ( (curValue == '^' ) || (curValue == '*') || (curValue == '/') || (curValue == '+' ) || (curValue == '-') )
operator = true;
return operator;
}
public String getRemainingOp(StringBuffer postfixStrBuf)
{
char popped=' ';
while ( !(os.isEmpty()) )
{
opped = ((Character)os.pop());
postfixStrBuf.append(popped);
}
postfix=postfixStrBuf.toString();
return postfix;
}
}
I will only post how the inner loop should look like (without the castings everywhere):
if (curValue == '(') {
os.push(curValue);
} else if (curValue == ')') {
if(!os.isEmpty()) {
topped = os.pop();
while (!os.isEmpty() && (topped != '(')) {
postfixStrBuf.append(topped);
topped = os.pop();
}
}
} else if (isOperator(curValue)) {
if (os.isEmpty()) {
os.push(curValue);
} else {
while(!os.isEmpty() && (priority(os.top()) >= priority(curValue))) {
popped = os.pop();
postfixStrBuf.append(popped);
}
os.push(curValue);
}
} else if (curValue != ' ') {
postfixStrBuf.append(curValue);
}
Disclosure: it is pretty late already so I hope it is fine. You should fix the way variables are initialized and return of the getRemainingOp method.

Categories

Resources