Generic Stack not "pushing" necessary elements - java

I am currently in the process of debugging some code that I have for a problem that is supposed to check to see if there is a balance of opening and closing brackets. For this I am using the generic stack that I made to contain al the brackets. This is my main code
/* Following the specification in the README.md file, provide your
* SymbolBalance class.
* test these: { }’s, ( )'s, [ ]'s, " "’s, and /* * /’s are properly balanced
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SymbolBalance{
public static void main(String[] args){
if(args.length > 0){
try{
Scanner file = new Scanner(new File(args[0]));
MyStack<Character> balance = new MyStack<>();
String string;
char character;
char charNext;
int line = 0;
boolean beginning = true;
// the easiest way to understand/code this problem is by
// reading over each individual string, then each
// individual character of that string
while(file.hasNextLine()){
line++;
string = file.next();
for(int i = 0; i < string.length() - 1; i++){
character = string.charAt(i);
charNext = string.charAt(i + 1);
if(character == '[' || character == '{' ||
character == '(' || character == '/' &&
charNext == '*' || character == '/' &&
charNext == '*'){
balance.push(character);
}
else if(character == '*' && charNext == '/'){
if(balance.isEmpty()){
System.out.println("<"+i+">: Empty");
}
else if(balance.pop() != '*'){
System.out.println("<"+i+">: <"+character+">, <"+balance.pop()+">");
}
}
else if(character == ']'){
if(balance.isEmpty()){
System.out.println("<"+i+">: Empty");
}
else if(balance.pop() != '['){
System.out.println("<"+i+">: <"+character+">, <"+balance.pop()+">");
}
}
else if(character == '}'){
if(balance.isEmpty()){
System.out.println("<"+i+">: Empty");
}
else if(balance.pop() != '{'){
System.out.println("<"+i+">: <"+character+">, <"+balance.pop()+">");
}
}
else if(character == ')'){
if(balance.isEmpty()){
System.out.println("<"+i+">: Empty");
}
else if(balance.pop() != '('){
System.out.println("<"+i+">: <"+character+">, <"+balance.pop()+">");
}
}
else if(character == '"'){
if(beginning == true){
balance.push(character);
}
else{
if(balance.isEmpty()){
System.out.println("<"+i+">: Empty");
}
else if(balance.pop() != '('){
System.out.println("<"+i+">: <"+character+">, <"+balance.pop()+">");
}
beginning = true;
}
}
}
}
file.close();
}
catch(FileNotFoundException e){
System.out.println("No such file exists or cannot be found");
}
}
}
}
What happens is that once my code runs, there is an error where it says that my stack is empty (from my generic stack class). This leads me to think that my characters are not being pushed into the stack (hence the empty stack exception). I have looked over my generic stack code and I am fairly confident the issue is not in that file. Is there something wrong with my if statements or is this an issue of me not using scanner correctly and as such the file itself isn't being read correctly? As a side not I have seen the file that is supposed to be read and I know it is not empty so that also is not the issue.
I am aware this will probably be a silly mistake, but I cannot seem to distinguish it right now. I would appreciate any input.
Thanks!

Related

Is there a better way to write a java code for detecting valid parentheses in a String?

I tried to solve a problem in leetcode and im not able to pass all the test cases. I tried to use stack. Whenever there is an open parenthesis, I push it into the stack and whenever there is a close parentheses, I check and pop if the correct open parenthesis is present on the top of the stack.
I check if the stack is empty in the last
Problem statement:
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.
Stack<Character> stk = new Stack<Character>();
boolean check = true;
char temp;
if(s.length() == 1)
{
return false;
}
else if(s.length() == 0)
{
return true;
}
else
{
for(int i = 0 ; i < s.length() ; i++)
{
temp = s.charAt(i);
if(temp == '{' || temp == '(' || temp == '[')
{
stk.push(temp);
}
else if(temp == '}')
{
if(stk.peek() == '{')
{
stk.pop();
}
else
{
check = false;
}
}
else if(temp == ')')
{
if(stk.peek() == '(')
{
stk.pop();
}
else
{
check = false;
}
}
else if(temp == ']')
{
if(stk.peek() == '[')
{
stk.pop();
}
else
{
check = false;
}
}
}
if(check == false && stk.empty() == false)
{
return false;
}
else
{
return true;
}
}
You have simply not taken in consideration cases such as
()), where the stack can be empty when you receive a new closing paranthesis.
Simply add
!stk.isEmpty()&&
before each
stk.peek()
It's generally a good idea when working with vectors, matrix, etc. to verify if the element is within bounds and exists(or give internal reasoning as to why it isn't and why at least a check is necessary).
Also, sometimes you can have stuff such as
(, where the check doesn't meet a mismatching closing paranthesis to turn it into false. However, there is a mismatching opening paranthesis.
So the final part of the code has to be
if(check == false || stk.empty() == false)
instead of &&, I put ||
I've run it on the site and it works :) .
This code works on Leetcode. I've modified it so that instead of setting check to false, it just immediately returns false, since there's no point going through the whole string. It also checks if the stack is empty at each iteration. To avoid failing when the input starts with a closing parentheses, square bracket, or curly brace, it pushes the first character of the string onto the stack at the very start.
I've also improved it a bit by rejecting strings of odd lengths at the very start, which makes it run faster than 98.69% of all submissions to the Leetcode problem.
Stack<Character> stk = new Stack<Character>();
char temp;
int len = s.length();
if(len == 0) {
return true;
} else if (len % 2 == 1) {
return false;
}
stk.push(s.charAt(0));
for(int i = 1; i < len; i++) {
temp = s.charAt(i);
switch (temp) {
case '{':
case '(':
case '[':
stk.push(temp);
break;
case '}':
if (stk.peek() == '{') {
stk.pop();
break;
} else return false;
case ')':
if (stk.peek() == '(') {
stk.pop();
break;
} else return false;
case ']':
if (stk.peek() == '[') {
stk.pop();
break;
} else return false;
}
if (stk.isEmpty()) break;
}
return stk.isEmpty();
I hope you don't mind that I replaced your if-statements with a switch block. It's pretty much the same, but it looks clearer to me, at least. You can always change it back though, it'll work the same.
This seems to work fine:
public boolean isValid(String s) {
int n = s.length();
if (n == 0) return true;
if (n % 2 == 1) return false;
Stack<Character> st = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '{' || c == '[' || c == '(') {
st.push(c);
} else if (st.isEmpty()) { // no opening bracket stored
return false;
} else {
char prev = st.pop();
switch(c) { // matching open and close bracket
case '}': if (prev != '{') return false; else break;
case ']': if (prev != '[') return false; else break;
case ')': if (prev != '(') return false; else break;
}
}
}
return st.isEmpty(); // stack must be empty in the end - all pairs matched
}

Getting wrong output in a test case in Chech brackets in code

boolean Match(char c) {
if (this.type == '[' && c == ']')
return true;
if (this.type == '{' && c == '}')
return true;
if (this.type == '(' && c == ')')
return true;
return false;
}
Stack<Bracket> opening_brackets_stack = new Stack<Bracket>();
for (int position = 0; position < text.length(); ++position)
{
char next = text.charAt(position);
if (next == '(' || next == '[' || next == '{')
{
// Process opening bracket, write your code here
Bracket temp = new Bracket(next,position);
opening_brackets_stack.push(temp);
}
if (next == ')' || next == ']' || next == '}')
{
// Process closing bracket, write your code here
try{
Bracket item = opening_brackets_stack.pop();
if(!item.Match(next))
{ //not match
System.out.println(position+1);
return;
}
}
catch(EmptyStackException e){}
}
}
// Printing answer, write your code here
try{
if(opening_brackets_stack.isEmpty())
{
System.out.println("Success");
}
else {
Bracket item = opening_brackets_stack.pop();
//print position of first unmatched opening bracket
System.out.println(item.position+1);
}
}
catch (EmptyStackException e){}
}
i am getting wrong answer in cases like "}","()}" in which bracket is at last position.
i am supposed to get answer "1","3" respectively for above cases but i am getting "Success".
In all other cases, it works perfectly fine.
What should I do?
With a string like "}", your code tries to pop an opening brace from the stack. But the stack is empty so you get an EmptyStackException, and control is transferred to your exception handler. Which does nothing.
Rather than trying to catch an exception, check to see if the stack is empty. If it is, then you know that you have too many closing braces. Treat it the same way you'd treat a false return from item.Match.

Character stack to check matching brackets no errors but also doesnt appear to do anything

I took a half a year off from programming and now Im just refreshing my memory w super basic little interview questions...and Ive been stuck for 2 days on the first one.. Below is my code can someone just hint to me why the program shows no errors but upon compilation does nothing? It should ignore text characters but Im not even there yet
public class bracketCheck {
public static void main(String[] args) {
Stack <Character> s = new <Character> Stack();
Scanner input = new Scanner(System.in);
String buff;
System.out.println("please enter brackets & text");
buff = input.nextLine();
input.close();
int count = 0;
boolean cont = true;
Character stackTop;
Character current = buff.charAt(count);
do {
if(current == ')' || current== '}' || current== ']') {
s.push(current);
count++;
}
else if(current== '(' || current== '{' || current== '[') {
stackTop = s.pop();
cont = match(stackTop, current);
}
}
while(s.isEmpty() == false /*&& cont =true*/);
if(s.isEmpty())
System.out.println("bout time......");
}
private static boolean match(Character top , Character not) {
if(top == ')' && not == '(')
return true;
else if(top == ']' && not == '[')
return true;
else if(top == '}' && not == '{')
return true;
else
return false;
}
}
I saw some issues in your code, this is my fixed version of it
import java.util.Scanner;
import java.util.Stack;
// use Capital letters in the beginning of class names
public class BracketCheck {
public static void main(String[] args) {
Stack<Character> stack = new Stack<>();
Scanner input = new Scanner(System.in);
String buff;
System.out.println("please enter brackets & text");
buff = input.nextLine();
input.close();
// using java8 makes iterating over the characters of a string easier
buff.chars().forEach(current -> {
// if <current> is an opening bracket, push it to stack
if (current == '(' || current == '{' || current == '[') {
stack.push((char) current);
}
// if <current> is a closing bracket, make sure it is matching an opening
// bracket or alert and return
else if (current == ')' || current == '}' || current == ']') {
if (!match(stack, (char) current)) {
System.out.println("no good");
return;
}
}
});
// if, after we finished iterating the string, stack is empty, all opening
// brackets had matching closing brackets
if (stack.isEmpty()) {
System.out.println("bout time......");
}
// otherwise, alert
else {
System.out.println("woah");
}
}
private static boolean match(Stack<Character> stack, Character closer) {
// if stack is empty, the closer has no matching opener
if (stack.isEmpty()) {
return false;
} else {
// get the most recent opener and verify it matches the closer
Character opener = stack.pop();
if (opener == '(' && closer == ')')
return true;
else if (opener == '[' && closer == ']')
return true;
else if (opener == '{' && closer == '}')
return true;
else
return false;
}
}
}

How to write a program that balances the symbols?

I am writing a program for hw. We are supposed to balance these symbols
l { }'s, ( )'s, [ ]'s, " "'s, and /* */'s and ignore string literals and comments blocks, but I don't know how to do that. My code is partially working, but when it comes to { } it can't tell. It also has problems dealing with /* */. I'm stuck and don't know which way to go.
For example, given:
public class Test {
public static final void main(String[ ) args) {
System.out.println("Hello.");
}
}
It prints two } mismatches because { is not immediately before }. We are required to push the symbols onto a stack and pop them to compare. We also need to write our own stack method called MyStack.java
I provided the main here:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SymbolBalance {
public static void main(String[] args){
if(args.length>0){
try{
Scanner input = new Scanner(new File (args[0]));
MyStack<Character> ms = new MyStack<>();
String str;
char ch;
while(input.hasNext()){
str = input.next();
for(int i=0;i<str.length();i++){
ch = str.charAt(i);
if(ch == '{'||ch =='(' || ch=='[' ||ch=='"'||
(ch == '/'&&i<str.length() -1&&str.charAt(i+1)=='*'))
{
ms.push(ch);
}
else if (ch==')'){
if(ms.isEmpty()||ms.pop()!= '('){
System.out.println(") is mismatched");
}
}
else if(ch == ']'){
if(ms.isEmpty() || ms.pop() != '['){
System.out.println("] is mismatched");
}
}
else if(ch == '}'){
if(ms.isEmpty() || ms.pop() != '{'){
System.out.println("} is mismatched");
}
}
else if(ch == '*' && i<str.length()-1&&str.charAt(i+1) == '/'){
if(ms.isEmpty() || ms.pop() != '*'){
System.out.println("*/ is mismatched");
}
}
else if(ch == '"'){
if(ms.isEmpty() || ms.pop() != '"'){
System.out.println(" \"\" is mismateched");
}
}
}
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("Cannot find file");
e.printStackTrace();
}
}
else{
System.out.println("No command line argument");
}
}
}
Your program is 99% correct. The only part where there is a logical fallacy is on the special case of a double quote.
A double quote is a special symbol in the sense that it is the same symbol to denote both start and end of a quotation. The other symbols in your list have different start and end notations. E.g. a bracket. Start bracket is denoted by '[' and end one is denoted by ']'. However for a double quote, " can denote either a start or an end of a quote.
Since a double quote mark is a special symbol, you need to handle it in a special way. When you push or pop a double quote symbol to your MyStack stack, you need to keep a track of whether it is a start or an end. There could be many ways to keep a track of it. I would suggest a boolean flag indicating the same. You need to flip the flag every time you push or pop a double quote to your stack.
Following is a working instance of your program with my revisions:
public static void main(String[] args){
if(args.length>0){
try{
Scanner input = new Scanner(new File (args[0]));
MyStack<Character> ms = new MyStack<>();
String str;
char ch;
boolean quoteStart = true; //Flag to indicate quote start or end
while(input.hasNext()){
str = input.next();
for(int i=0;i<str.length();i++){
ch = str.charAt(i);
//Remove the " from the following condition. Handle it later.
if(ch == '{'||ch =='(' || ch=='[' ||
(ch == '/'&&i<str.length() -1&&str.charAt(i+1)=='*'))
{
ms.push(ch);
}
else if (ch==')'){
if(ms.isEmpty()||ms.pop()!= '('){
System.out.println(") is mismatched");
}
}
else if(ch == ']'){
if(ms.isEmpty() || ms.pop() != '['){
System.out.println("] is mismatched");
}
}
else if(ch == '}'){
if(ms.isEmpty() || ms.pop() != '{'){
System.out.println("} is mismatched");
}
}
else if(ch == '*' && i<str.length()-1&&str.charAt(i+1) == '/'){
if(ms.isEmpty() || ms.pop() != '*'){
System.out.println("*/ is mismatched");
}
}
//Handle the quote here
else if(ch == '"'){
if(quoteStart == true) {
ms.push(ch);
quoteStart = false;
}
else {
if(ms.isEmpty() || ms.pop() != '"'){
System.out.println(" \"\" is mismateched");
}
quoteStart = true;
}
}
}
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("Cannot find file");
e.printStackTrace();
}
}
else{
System.out.println("No command line argument");
}
}

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.

Categories