Balance Check in Java - 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.

Related

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)

Token pairs matching with Java

The problem states that you need to match up the tokens (like a pair []. Ex: ([)] is incorrect, ([]) is correct, ()(} is incorrect, """" is correct, """ is incorrect. I think the logical error might be in the if statements, in the for-loop. Tokens are identified for this problem as: "(quotes),[,],{,},(,).
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
public class matchingtokens {
public static void main(String[] args) throws IOException {
Scanner in=new Scanner(new File("File.txt"));
while (in.hasNext()) {
String input= in.nextLine();
System.out.println("" + input);
String[]a = input.trim().split("");
ArrayList<Character>listOfQuotes =new ArrayList<Character>();
ArrayList<Character>parenPart =new ArrayList<Character>();
for (int i = 0; i < input.length();i++) {
if (input.charAt(i) == '['|| input.charAt(i) == ']' || input.charAt(i) == '{' || input.charAt(i) == '}' || input.charAt(i) == '(' || input.charAt(i) == ')') {
parenPart.add(input.charAt(i));
} else if (input.charAt(i) == '\"') {
listOfQuotes.add(input.charAt(i));
} else {
// i++;
}
}
System.out.println("quotes: " + listOfQuotes);
System.out.println("others: " + parenPart);
if (listOfQuotes.size() % 2 == 0) {
if (parenPart.size() % 2 == 0) {
if (parenPart.get(0) == ']' || parenPart.get(0) == '}' || parenPart.get(0) == ')') {
System.out.println("INCORRECT:: CANNOT BEGIN WITH CLOSING");
break;
} else {
for (int i = 0; i < parenPart.size() - 1; i++) {
if (parenPart.get(i) == '}' && parenPart.get(i-1) == '{') {
parenPart.remove(i);
parenPart.remove(i-1);
i = i - 2;
} else if (parenPart.get(i) == ']' && parenPart.get(i-1) == '[') {
parenPart.remove(i);
parenPart.remove(i-1);
i = i - 2;
continue;
} else if (parenPart.get(i) == ')' && parenPart.get(i-1) == '(') {
parenPart.remove(i);
parenPart.remove(i-1);
i = i - 2;
continue;
} else {
if(parenPart.size()== 0) {
System.out.println("CORRECT");
}else {
System.out.println("INCORRECT:: TOKENS DON'T MATCH UP");
}
}
}
} }else {
System.out.println("INCORRECT:: BRACKETS DON'T MATCH");
break;
}
} else {
System.out.println("INCORRECT:: \" DOES NOT MATCH \"");
break;
}
}
}
}
I'm not sure I understood what you mean but try
for (int i = 0; i < parenPart.size(); i++) {
//parenPart.size() not parenPart.size()-1
if (parenPart.get(i) == '}' && parenPart.get(i-1) == '{') {
parenPart.remove(i);
parenPart.remove(i-1);
i = i - 2;
} else if (parenPart.get(i) == ']' && parenPart.get(i-1) == '[') {
parenPart.remove(i);
parenPart.remove(i-1);
i = i - 2;
continue;
} else if (parenPart.get(i) == ')' && parenPart.get(i-1) == '(') {
parenPart.remove(i);
parenPart.remove(i-1);
i = i - 2;
continue;
} else {
}
}
//out of the for loop
if(parenPart.size()== 0) {
System.out.println("CORRECT");
}else {
System.out.println("INCORRECT:: TOKENS DON'T MATCH UP");
}

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");
}
}

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

Java .add(value) with lists

Basically I've got an input string, my test string is '5 + 4' and I want to check character by character to create a list in the form [5,+,4], ie white spaces are ignored. Also, if my test string was '567+5-1' it would output [567,+,5,-,1] by concatenating the numbers together. Unfortunately, it won't let me do .add(inputChar) to my returnValue, saying symbol not found... any ideas?
import java.util.*;
public class CharacterArray {
public List<String> splitToChar(String s) {
List<String> returnValue = new LinkedList<String>();
char[] chars = s.toCharArray();
System.out.println(chars);
int currentNumber;
for (char inputChar : chars) {
if (Character.isDigit(inputChar) == true) {
currentNumber += inputChar;
} else if (inputChar == '.') {
currentNumber += inputChar;
} else if (inputChar == '+') {
returnValue.add(inputChar);
} else if (inputChar == '-') {
returnValue.add(inputChar);
} else if (inputChar == '/') {
returnValue.add(inputChar);
} else if (inputChar == '*') {
returnValue.add(inputChar);
} else if (inputChar == '(') {
returnValue.add(inputChar);
} else if (inputChar == ')') {
returnValue.add(inputChar);
} else {
System.out.println("Incorrect input symbol");
}
}
return returnValue;
}
}
import java.util.*;
public class CharacterArray {
public List<String> splitToChar(String s) {
List<String> returnValue = new LinkedList<String>();
char[] chars = s.toCharArray();
System.out.println(chars);
String currentNumber = "";
for (char inputChar : chars) {
if (Character.isDigit(inputChar) == true) {
currentNumber += inputChar;
} else if (inputChar == '.' ||
inputChar == '+' ||
inputChar == '-' ||
inputChar == '/' ||
inputChar == '*' ||
inputChar == '(' ||
inputChar == ')') {
if (currentNumber.length() > 0){
returnValue.add(currentNumber);
}
currentNumber = "";
returnValue.add(""+inputChar);
} else {
System.out.println("Incorrect input symbol");
}
}
if (currentNumber.length() > 0){
returnValue.add(currentNumber);
}
return returnValue;
}
}
By the way, your currentNumber should be a String
how about .add(String.valueOf(inputChar)) ?
You can't add a char to a List<String> perhaps what you are trying to do is like
String currentNumber = "";
for (char inputChar : chars) {
if (Character.isDigit(inputChar) || inputChar == '.') {
currentNumber += inputChar;
} else if ("+-/*()".indexOf(inputChar) >= 0) {
if (currentNumber.length() > 0) returnValue.add(currentNumber);
currentNumber = "";
returnValue.add("" + inputChar);
} else if (inputChar != ' ') {
System.out.println("Incorrect input symbol '"+inputChar+"'");
}
}
if (currentNumber.length() > 0) returnValue.add(currentNumber);
Your returnValue is a List<String> but you are trying to add a char to the list. You can fix this by converting inputChar to a String when adding it to the list by using String.valueOf(inputChar).

Categories