how to check number exists between braces - java

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)

Related

Code running to slow to pass . Can't figure out why

I have to solve this exercise and I am pretty new to coding. The task is:
In this problem, the input to your program is an array of N characters, each of which is either (, ), [ or ], and your program must return true if the parentheses are properly matched, and false if they are not.
The code works and solves all the tests correct, but it is to slow to pass overall and I can't figure out why. What can I do to improve the speed of the code? Thank in advance.
public class Dyck {
public boolean checkParentheses(ArrayList<Character> input) {
Stack<Character> s = new Stack<>();
Stack<Character> s2 = new Stack<>();
for(var c : input){
s.add(0, c);
}
Character c2;
Character c = s.pop();
if (c != ')' && c != ']') {
s2.add(c);
}
var size = s.size();
for (int i = 0; i < size; ++i) {
c = s.pop();
if (c == '[' || c == '(') {
s2.add(c);
}
if (c == ')') {
if (s2.isEmpty()) {
return false;
}
c2 = s2.pop();
if (c2 != '(') {
return false;
}
}
if (c == ']') {
if (s2.isEmpty()) {
return false;
}
c2 = s2.pop();
if (c2 != '[') {
return false;
}
}
}
if (s.isEmpty() && s2.isEmpty()) {
return true;
}
return false;
}

String Index Exception

I was trying to convert an expression from infix form to postfix form.I used String a, p , s for stack, postfix result expression, input expression respectively.
Every time I am getting this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at
java.lang.String.charAt(String.java:658) at
javaapplication4.A.conversion(A.java:50) at
javaapplication4.A.main(A.java:83)
Please help me how can I solve it.
Here is my code:
import java.util.Scanner;
public class A {
String a="(", s = "", p = "";
int i, n = 1, top = 0, pp = 0;
void push(char ch) {
a = a + ch;
top = n;
n++;
}
void pop() {
n--;
top--;
}
int prio(char ch) {
int f = -1;
if (ch == '(') {
f = 0;
} else if (ch == '+' || ch == '-') {
f = 1;
} else if (ch == '*' || ch == '/' || ch == '%') {
f = 2;
} else if (ch == '^') {
f = 3;
}
return f;
}
void conversion() {
System.out.print("Enter infix form: ");
Scanner sd = new Scanner(System.in);
s = sd.nextLine();
//System.out.println(s);
int t, j, sz;
sz = s.length();
for (i = 0; i < sz; i++) {
if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
p = p + s.charAt(i);
pp++;
} else if (s.charAt(i) == '(') {
push('(');
} else if (s.charAt(i) == '-' || s.charAt(i) == '+' || s.charAt(i) == '*' || s.charAt(i) == '/' || s.charAt(i) == '%' || s.charAt(i) == '^') {
j = prio(s.charAt(i));
t = prio(a.charAt(top));
//System.out.println(t+" "+j);
while (j <= t) {
p = p + a.charAt(top);
pp++;
pop();
t = prio(a.charAt(top));
}
push(s.charAt(i));
} else if (s.charAt(i) == ')') {
while (a.charAt(top) != '(') {
p = p + a.charAt(top);
pp++;
pop();
}
pop();
}
}
while (a.charAt(top) != '(') {
p = p + a.charAt(top);
pp++;
pop();
}
pop();
}
void postfix() {
System.out.print("postfix form is: ");
System.out.println(p);
}
public static void main(String args[]) {
A h = new A();
h.conversion();
h.postfix();
//System.out.println(h.a);
//System.out.println(h.s);
}
}
Can you confirm if the error is here?
while (a.charAt(top) != '(')
Inside the loop you continuously pop(), which decrements from top, which has the risk of going negative if a match is never found. Even if the error is not here, it should check for that condition.
You may have made an extra pop() definition. Can you check this?

Trying to implement a stack and the bracket matching problem but cannot figure out some semantic errors

I am required to write my own stack using an array which then I have to implement the bracket matching problem.
This is my algorithm: if we're given the string: "(())" it is returning "not balanced" when it should say it is "balanced". If you look over at BracketCheck.java near the end it tests whether the stack is empty where if it is it should return true and say the given string: "(())" is balanced. I am having problems debugging it and the result of the operation is incorrect.
Here is my stack and main class code:
public class Stack {
// instance fields:
private char array[]; // our array
private int topOfStack; // this indicates the value for each position
// overloaded constructor:
public Stack(int size) {
this.array = new char[size]; // here we instantiate a new char type array.
this.topOfStack = -1; // we set the starting position of the topOfStack to -1.
}
// push method:
public void push(char character) {
if(isFull() == true) {
System.out.println("Stack overflow error.");
}
else {
topOfStack++;
array[topOfStack] = character;
}
}
// pop method:
public char pop() {
if(isEmpty() == true) {
//System.out.println("Overflow.");
return '\0';
}
else {
char c = array[topOfStack];
topOfStack--;
return c;
}
}
// top method:
public int top() {
if(isEmpty() == true) {
System.out.println("The stack is empty.");
return 0;
}
else {
return array[topOfStack]; // returns the top element in the stack.
}
}
// size method:
public int size() {
return topOfStack + 1;
}
// isEmpty method:
public boolean isEmpty() {
if(topOfStack == -1) {
return true;
}
else {
return false;
}
}
// isFull method:
public boolean isFull() {
if(topOfStack == array.length -1 ) {
System.out.println("Stack if full.");
return true;
}
else {
return false;
}
}
BracketCheck.java
public class BracketCheck {
public static void main(String args[]) {
String text = "(())";
//boolean check = isBalanced(text);
if(isBalanced(text) == true) {
System.out.println("Balanced.");
}
else {
System.out.println("Not balanced");
}
}
public static boolean isBalanced(String text) {
Stack stack = new Stack(25); // for simplicity our stack is going to be a size of 25.
char[]arr = text.toCharArray(); // convert our string to a set of characters in an array.
// here we are looping through our text
for(int i = 0; i < arr.length; i++) {
if(arr[i] == '{' || arr[i] == '(' || arr[i] == '[') {
stack.push(arr[i]);
}
else if(arr[i] == '}' || arr[i] == ')' || arr[i] == ']') {
if(stack.isEmpty()) {
return false; // if empty then return false.
}
else if((stack.pop() == '(' && arr[i] != ')') || (stack.pop() == '{' && arr[i] != '}') || (stack.pop() == '[' && arr[i] != ']')) {
return false; // here we return false because this tells us that there is a mismatch and not balanced. Also if we did pop out the brace and it was equal
// to it's corresponding closing brace then it will just continue the loop other return false to indicate it is unbalanced.
}
}
}
if(stack.isEmpty()) {
return true; // after looping through the text if the stack turns out to be empty then this shows that there the text is balanced indeed because
}
else {
return false;
}
}
}
In this condition
else if((stack.pop() == '(' && arr[i] != ')') || (stack.pop() == '{' && arr[i] != '}') || (stack.pop() == '[' && arr[i] != ']')) {
You pop 3 times, so you extract 3 different elements from your stack. To fix it, pop once and save popped element in local variable:
if(stack.isEmpty()) {
return false; // if empty then return false.
}
else {
char element = stack.pop();
if((element == '(' && arr[i] != ')') || (element == '{' && arr[i] != '}') || (element == '[' && arr[i] != ']')) {
return false;
}
}

Balance Check in Java

This is code for checking balance symbol.
However, when I try to fit in a Tester,
It does not show the anwer correctly.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BalanceCheck {
private static Scanner in;
public static void main(String[] args){
if(args.length > 0){
System.out.println(args[0]);
try {
in = new Scanner(new File(args[0]));
MyStack<Character> stack = new MyStack<>();
String str;
char ch;
while(in.hasNext()){
str = in.next();
for(int i = 0; i < str.length(); ++i){
ch = str.charAt(i);
if(ch == '(' || ch == '[' || ch == '{' ||
(ch == '/' && i < str.length() - 1 && str.charAt(i+1) == '*')){
stack.push(ch);
}
else if(ch == ')'){
if(stack.isEmpty() || stack.pop() != ch){
System.out.println(") is mismatched");
return;
}
}
else if(ch == ']'){
if(stack.isEmpty() || stack.pop() != ch){
System.out.println("] is mismatched");
return;
}
}
else if(ch == '}'){
if(stack.isEmpty() || stack.pop() != ch){
System.out.println("} is mismatched");
return;
}
}
else if(ch == '*' && i < str.length() - 1 && str.charAt(i+1) == '/'){
if(stack.isEmpty() || stack.pop() != '/'){
System.out.println("*/ is mismatched");
return;
}
}
else if(ch == '"'){
if(stack.isEmpty() || stack.top() == '"'){
if(!stack.isEmpty())
stack.pop();
}
else{
stack.push(ch);
}
}
}
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else{
System.out.println("Command line argument is not provided..");
}
}
}
For instance, if I compile this tester,
/*this tests an unbalanced [ operator*/
public class Test1 {
/* this is the main method */
public static void main(String[ ) args) {
String ghana = "hello";
int test = testing();
}
public int testing() {
/*checking this too */
/* and this */
return 1;
}
}
It should show [ is mismatched. But, it shows /* is mismatched.
Please let me know solution.
And I have to create a Tester file for this code above.
How can I code a tester for this?
Thanks,
Think about what happens with the very first line:
/*this tests an unbalanced [ operator*/
When you hit the '*/', there is a '[' on the top of the stack.
You need to track when you are inside a comment so that you can ignore everything until the end.
Whenever you have an issue like this, you need to use a debugger.

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 == ']';
}

Categories