Balancing Parenthesis for Lab Project - java

import stack.RStack;
public class Expressions {
private RStack data;
public Expressions() {
}
public boolean checkbalance(String expression) {
char charAt;
int i, len;
len = expression.length();
for(i = 0; i < len; i++) {
charAt = expression.charAt(i);
if(charAt == '(')
push(charAt);
else if(ch == ')') {
if(isEmpty())
return false;
else if((char)peek() == '(')
pop();
else
return false;
}
}
if(isEmpty())
return true;
else
return false;
}
public int precedence(char c) {
if((c == '*') || (c == '/'))
return 2;
else if((c == '+') || (c == '-'))
return 1;
else
return 0;
}
public boolean isOperand(char c) {
if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
return true;
else
return false;
}
public String infixToPostfix(String infix) {
char c;
int len, i;
String postfix = "";
len = infix.length();
for(i = 0; i < len; i++) {
c = infix.charAt(i);
if(isOperand(c))
postfix = postfix + c;
else if(c == '(')
push(c);
else if(c == ')') {
while((char)peek() != '(')
postfix = postfix + pop();
pop();
} else {
while(!isEmpty() && (precedence(c) <= precedence((char)peek())))
postfix = postfix + pop();
push(c);
}
}
while(!isEmpty())
postfix = postfix + pop();
return postfix;
}
public RStack getData() {
return data;
}
public void setData(RStack data) {
this.data = data;
}
}
Any idea on why do i always get "The method push(char) is undefined for the type Expressions", "the method peek() is undefined for the type Expressions", "The method isEmpty() is undefined for the type Expressions" and "The method pop() is undefined for the type Expressions"? when im trying to balance parenthesis for lab project and I always run into this issue

Your calls to push and pop do not exist. Therefore, the compiler complains.
If you meant to call those methods on your own class Expressions, you’ll need to define such methods. Do like you did with defining precedence and isOperand. See The Java Tutorials by Oracle.
If you meant to call those methods on an instance of another class, such as your mysterious RStack class, then you will need a reference to such an instance before you can call the methods. See The Java Tutorials.
By the way, the char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most characters.
To work with individual characters, use code point integer numbers. You’ll find various codePoint methods on classes such as String, StringBuilder, and Character.

Related

Palindrome Stack

I wrote this method to check to see if a words is a palindrome, but when it is a palindrome it keeps returning false
public boolean isPalindrome(String s){
int i;
int n = s.length();
Stack <Character> stack = new Stack <Character>();
for (i = 0; i < n/2; i++)
stack.push(s.charAt(i));
if (n%2 == 1)
i++;
while(!stack.empty( )) {
char c = stack.pop( );
if (c != s.charAt(i));
return false;
}
return true;
}
I'm not sure why you're not using { } brackets. Try to learn proper Java conventions early.
if (c != s.charAt(i)); // <- this semicolon is your problem
return false;
Is equivalent to:
if (c != s.charAt(i)) {
// Do nothing
}
// Do this no matter what
return false;
Furthermore, the logic on your for-loop may be flawed for similar reasons. Remove your semicolon, and better yet, practice always using brackets:
if (c != s.charAt(i)) {
return false;
}
#jhamon also points out that you never actually increment i in your while loop:
while(!stack.empty( )) {
char c = stack.pop( );
if (c != s.charAt(i)) {
return false;
}
i++;
}

how to check number exists between braces

import java.util.Stack;
import java.util.Scanner;
public class CheckValidLocationofParenthensies {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter five data");
String input1 = scanner.next();
balancedParenthensies(input1);
}
public static boolean balancedParenthensies(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' ) {
stack.push(c);
if(c == '[') {
newvalueforforward(s,']', i);
}
if(c == '{') {
newvalueforforward(s,'}', i);
}
if(c == '(') {
newvalueforforward(s,')', i);
}
} else if(c == ']') {
if(stack.isEmpty() || stack.pop() != '[') {
newvalue(s,'[', i);
return false;
}
} else if(c == ')') {
if(stack.isEmpty() || stack.pop() != '(') {
newvalue(s,'(', i);
return false;
}
} else if(c == '}') {
if(stack.isEmpty() || stack.pop() != '{') {
newvalue(s,'{', i);
return false;
}
}
}
return stack.isEmpty();
}
public static void newvalueforforward(String userval,char value,int decremntval) {
for(int i = 0; i < userval.length(); i++){
StringBuilder newvalue = new StringBuilder(userval);
int location=i;
newvalue.insert(i, value);
boolean valid= checkingnewvalueisValidorNot(newvalue, location);
location=i+1;
if(valid) {
System.out.println(newvalue+" "+""+location);
}
}
}
public static void newvalue(String userval,char value,int decremntval) {
for(int i = decremntval; i >= 0; i--){
StringBuilder newvalue = new StringBuilder(userval);
int location=decremntval - i;
newvalue.insert(decremntval - i, value);
boolean valid= checkingnewvalueisValidorNot(newvalue, location);
if(valid) {
System.out.println(newvalue+" "+""+location);
}
}
}
public static boolean checkingnewvalueisValidorNot(StringBuilder userval,int validpath) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < userval.length(); i++) {
char c = userval.charAt(i);
if(c == '[' || c == '(' || c == '{' ) {
stack.push(c);
} else if(c == ']') {
if(stack.isEmpty() || stack.pop() != '[') {
return false;
}
} else if(c == ')') {
if(stack.isEmpty() || stack.pop() != '(') {
return false;
}
} else if(c == '}') {
if(stack.isEmpty() || stack.pop() != '{') {
return false;
}
}
}
return stack.isEmpty();
}
}
Above is the code i have written to check whether input string contains all balanced brackets if it is not balanced then get missing bracket and place bracket in all index then again check whether string is balanced or not.
I got valid output but problem is between i bracket there should be a intergers
here is input and outputs
input missing outputs
{[(2+3)*6/10} ] {[](2+3)*6/10} 3 not valid(no numbres btn bracket)
{[(2+3)]*6/10} 8 valid
{[(2+3)*]6/10} 9 not valid(after * no number)
{[(2+3)*6]/10} 10 valid
{[(2+3)*6/]10} 11 not valid( / before bracket)
{[(2+3)*6/1]0} 12 not valid( / btn num bracket)
{[(2+3)*6/10]} 13 valid
i am failing to do proper validation to my output.
Before the bracket there may be:
number
closing bracket
After the bracket there may be:
operator
closing bracket
end of expression
(ignoring any whitespace)

Java Stack Boolean Output Customization?

So what I have is this slightly modified version of a code that's here a hundred times over for Java Stack Balancing.
import java.util.Stack;
public class Main {
public static String testContent = "{(a,b)}";
public static void main(String args[])
{
System.out.println(balancedParentheses(testContent));
}
public static boolean balancedParentheses(String s)
{
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' )
{
stack.push(c);
}else if(c == ']')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '[') return false;
}else if(c == ')')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '(') return false;
}else if(c == '}')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '{') return false;
}
}
return stack.isEmpty();
}
}
What I'd like to do is customize the output such that it would output something like "balanced" or "imbalanced" instead of true/false. Trying to replace return false; with a System.println containing 'balanced' gives me a whole lot of output lines I didn't want. Been searching around here for about an hour and some change and couldn't quite find the answer I was looking for. Any insight?
You could use something like
System.out.println(balancedParentheses(testContent) ? "balanced" : "imbalanced");
OR if you want a method that returns a String wrap the logic in another method
String isBalanced(String expression) {
return balancedParentheses(expression) ? "balanced" : "imbalanced"
}
and in main()
System.out.println(isBalanced(testContent));
Also you could write the code something like this
public static boolean balancedParentheses(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '[' || c == '(' || c == '{') {
stack.push(c);
} else if (c == ']' || c == ')' || c == '}') {
if (stack.isEmpty() || !matches(stack.pop(), c))
return false;
}
}
return stack.isEmpty();
}
private static boolean matches(char opening, char closing) {
return opening == '{' && closing == '}' ||
opening == '(' && closing == ')' ||
opening == '[' && closing == ']';
}

Why isn't this program running properly? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
The assignment was to create a postfix to infix converter using Stacks. The program compiles properly but when I tried to make a demo class, I received a null point exception line 32. Please share any observations, better coding conventions, or solutions.
import java.util.Stack;
public class PostfixtoInfix {
private String expression;
private Stack<Character> s;
Character pOpen = new Character('(');
Character pClose = new Character(')');
public String PostfixtoInfix(String e) {
expression = e;
String output = "";
for (int i = 0; i < e.length(); i++) {
char currentChar = e.charAt(i);
if (isOperator(currentChar)) {
while (!s.empty() && s.peek() != pOpen
&& hasHigherPrecedence(s.peek(), currentChar)) {
output += s.peek();
s.pop();
}
s.push(currentChar);
} else if (isOperand(currentChar)) {
output += currentChar;
} else if (currentChar == '(') {
s.push(currentChar);
} else if (currentChar == ')') {
while (!s.empty() && s.peek() != pClose) {
output += s.peek();
s.pop();
}
}
while (!s.empty()) {
output += s.peek();
s.pop();
}
}
return output;
}
public boolean isOperator(char c) {
if (c == '+' || c == '-' || c == '/' || c == '*' || c == '^')
return true;
return false;
}
public boolean isOperand(char c) {
if (c >= '0' && c <= '9')
return true;
if (c >= 'a' && c <= 'z')
return true;
if (c >= 'A' && c <= 'Z')
return true;
return false;
}
public int getOperatorWeight(char operator) {
int weight = -1;
switch (operator) {
case '+':
case '-':
weight = 1;
break;
case '*':
case '/':
weight = 2;
break;
case '^':
weight = 3;
}
return weight;
}
public boolean hasHigherPrecedence(char operator1, char operator2) {
int op1 = getOperatorWeight(operator1);
int op2 = getOperatorWeight(operator2);
if (op1 == op2) {
if (isRightAssociative(operator1))
return false;
else
return true;
}
return op1 > op2 ? true : false;
}
public boolean isRightAssociative(char op) {
if (op == '^')
return true;
return false;
}
}
To fix the NPE initialize your objects. Unlike C++, Stack<Character> s; is equivalent to Stack<Character> s = null;; not to Stack<Character> s = new Stack<>();!
Beware of == and != not behaving as you might expect for boxed objects.
Character a = new Character('A');
Character aa = new Character('A');
System.out.println(a == aa);
gives the (correct!) answer false.
They are different objects. If you want to compare for equality, use either:
System.out.println(a.equals(aa));
System.out.println((char)a==(char)aa);
The first uses an explicit method for comparing the object contents. The second one avoids this problem by using non-object primitives, where equality is bitwise, not reference-equality.
It appears that you declare a private member s, never assign anything to it, and then attempt to use it in expressions like s.empty() and s.pop(). If nothing is ever assigned to s, then it is null, and attempting to call a method on it will result in a NullPointerException.
To create an empty stack, you probably want to change the declaration to:
private Stack <Character> s = new Stack<Character>();
First of all, you have a method looking like a constructor:
public String PostfixtoInfix(String e) {
try changing it to something else, like:
public String transform(String e) {
Second, your s field never gets assigned a stack. Put
s = new Stack<Character>();
in your constructor. Also, new Character('a') != new Character('a'), because that will bypass automatic (pillowweight cached) boxing. Use instead just simple chars as pOpen and pClose.
Your access modifier may be preventing the program to access the stack.
Change:
private Stack <Character> s;
to:
protected Stack <Character> s;
Read more here

Analyze a string of characters in java for format A^nB^n

I have a string of characters with As and Bs that I need to analyze for a Language A^nB^n. I can use the following code to work most of the time but when there is a letter that is not an "A" or "B" it may still return true, for example: AABACABAA should not be true, but it says it is. AABB is true; AABBAABB is not true. I have to use stacks and am not allowed to use counting.
public static boolean isL2(String line){
// set up empty stacks
Stack L2Stack = new Stack();
// initialize loop counter
int i = 0;
int n = line.length();
/* Push all 'A's to a_stack */
while ((i < line.length()) && (line.charAt(i) == 'A')) {
char ch = line.charAt(i);
L2Stack.push(ch);
i++;
}
/* Pop an 'A' for each consecutive 'B' */
while ((i < line.length()) && (line.charAt(i) == 'B')) {
if (!L2Stack.empty()){
L2Stack.pop();
i++;
}
else
return false;
}
if (i == n && !L2Stack.empty()){
return false; // more As than Bs
}
if (i != n && L2Stack.empty()){
return false; //more Bs than As
}else
return true;
}
if (i != n && L2Stack.empty()) {
return false; //more Bs than As
}
Should be
if (i != n) {
return false;
}
Since if you haven't finished reading all the characters, you can't return true, regardless of whether or not the stack is empty.
I'm assuming that AAABBBA should return false.
That change would also handle illegal characters.

Categories