Special characters in a string [JAVA] - java

folks, the method below would throw an Exception if other character than "01xX \t"(including whitespace and \t inside a passed String) is found. If I have this String "1 x \tX 00", the method should return [1,X,X,X,X,X,X,X,0,0] but Im getting only [1,X,X,0,0] in which the 'whitespace' and '\t' somehow are not getting included. 'Whitespace' and '\n' also should return 'X'. Please could smb help me?
//Here's the test case that I'm failing
#Test (timeout=3000) public void signal13(){
String inp = "1 x \tX 00";
List<Signal> expecteds = Signal.fromString(inp);
assertEquals(expecteds, Arrays.asList(new Signal[]{Signal.HI, Signal.X, Signal.X, Signal.LO, Signal.LO}));
}
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public enum Signal {
HI, LO, X;
public Signal invert()
{
if(this == HI)
return LO;
else if(this == LO)
return HI;
else if(this == X)
return X;
return this;
}
public static Signal fromString(char c)
{
if(c == '1')
return HI;
else if(c == '0')
return LO;
else if(c == 'X')
return X;
else if(c == 'x')
return X;
else
throw new ExceptionLogicMalformedSignal(c, "Invalid character!");
}
public static List <Signal> fromString(String inps)
{
List<Signal> values = new ArrayList<Signal>();
for(int i = 0; i < inps.length(); i++)
{
if(inps.charAt(i) == '1')
values.add(HI);
else if(inps.charAt(i) == '0')
values.add(LO);
else if(inps.charAt(i) == 'X')
values.add(X);
else if(inps.charAt(i) == 'x')
values.add(X);
else if(inps.charAt(i) == ' ')
values.add(X);
else if(inps.charAt(i) == '\t')
{
values.add(X);
values.add(X);
}
else
throw new ExceptionLogicMalformedSignal(inps.charAt(0), "Invalid character!");
}
return values;
}
#Override
public String toString()
{
if(this == HI)
return "1";
else if(this == LO)
return "0";
else if(this == X)
return "X";
return "Error here!";
}
public static String toString(List<Signal> sig)
{
String result = "";
ArrayList<Signal> temp = new ArrayList<>();
for(Signal x: sig)
{
temp.add(x);
}
for(int i = 0; i < temp.size(); i++)
{
if(temp.get(i) == HI)
result += "1";
else if(temp.get(i) == LO)
result += "0";
else if(temp.get(i) == X)
result += "X";
}
return result;
}
}

Seem like the assertion is not correct, it's:
assertEquals(expecteds, Arrays.asList(new Signal[]{Signal.HI, Signal.X, Signal.X, Signal.LO, Signal.LO}));
while it should be :
List<Signal> actual = Signal.fromString(inp);
List<Signal> expected = Arrays.asList(new Signal[]{Signal.HI, Signal.X, Signal.X,Signal.X,Signal.X,Signal.X,Signal.X,Signal.X, Signal.LO, Signal.LO});
assertEquals(expected, actual);
Because the expected result is [1,X,X,X,X,X,X,X,0,0]

here is a modified version of your code that works as you need it...
private String fromString(String inps) throws Exception {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inps.length(); i++) {
if (inps.charAt(i) == '1') {
sb.append("1");
} else if (inps.charAt(i) == '0') {
sb.append("0");
} else if (inps.charAt(i) == 'X') {
sb.append("x");
} else if (inps.charAt(i) == 'x') {
sb.append("x");
} else if (inps.charAt(i) == ' ') {
sb.append("x");
} else if (inps.charAt(i) == '\t') {
sb.append("x");
sb.append("x");
} else {
throw new Exception("invalid character");
}
}
return sb.toString();
}
When you output fromString("1 x \tX 00") you get the result 1xxxxxxx00 as expected.
Hope this helps

Related

Recursive method to evaluate expressions just work when method is called once

I'm writing a code to valuate math expressions. The code just works when I call the methode once. But I have more than one expression to evaluate and it just break when I call the method more than two times. I get the following error:
-2
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:102)
at java.util.Stack.pop(Stack.java:84)
at Evaluate.parse(Evaluate.java:58)
at Evaluate.main(Evaluate.java:11)
I see that the code gives me the expected result (the -2) but what I'm doing wrong regarding the methode that gives me this error
My code:
public class Evaluate {
static Stack<Character> ops = new Stack<Character>();
static Stack<Integer> vals = new Stack<Integer>();
static int i = 0;
public static void main(String[] args) {
System.out.println(parse("(4-(7-1))"));
System.out.println(parse("8"));
System.out.println(parse("((1+1)*(2*2))"));
System.out.print("\n");
System.out.println(parse("(6/(3/2))"));
}
private static int parse(String expression) {
char[] tokens = expression.toCharArray();
while (tokens.length > i) {
char s = tokens[i];
if (s == '(') {
ops.push(tokens[i]);
} else if (s == '+' || s == '-' || s == '*' || s == '/') {
while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
vals.push(applyOp(ops.pop(), vals.pop(), vals.pop()));
ops.push(s);
} else if (s == ')') {
char op = ops.pop();
int v = vals.pop();
while (ops.peek() != '(')
vals.push(applyOp(ops.pop(), vals.pop(), vals.pop()));
ops.pop();
if (op == '+') {
v = vals.pop() + v;
} else if (op == '-') {
v = vals.pop() - v;
} else if (op == '*') {
v = vals.pop() * v;
} else if (op == '/') {
v = vals.pop() / v;
}
vals.push(v);
} else {
vals.push(Character.getNumericValue(s));
}
i++;
}
while (!ops.empty())
vals.push(applyOp(ops.pop(), vals.pop(), vals.pop()));
return vals.pop();
}
public static boolean hasPrecedence(char op1, char op2) {
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// A utility method to apply an
// operator 'op' on operands 'a'
// and 'b'. Return the result.
public static int applyOp(char op, int b, int a) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}

Operator changed to int during infix to postfix conversion

private DSAQueue parseInfixToPostfix(String equation) {
String result = "";
char operator = ' ';
DSAStack stack = new DSAStack();
DSAQueue queue = new DSACircular();
for (int i = 0; i < equation.length(); i++) {
char c = equation.charAt(i);
if (Character.isLetterOrDigit(c)) {
result += c;
}
else if (c == '(') {
stack.push(c);
}
else if (c == ')') {
while (!stack.isEmpty() && stack.top() != '(') {
result += stack.pop();
}
if (!stack.isEmpty() && stack.top() != '(') {
result = "Invalid expression";
}
else {
stack.pop();
}
}
else { //when meets operator
while (!stack.isEmpty() && (precedenceOf(c) <= precedenceOf((char) stack.top()))) {
if (stack.top() == '(') {
result = "Invalid expression";
}
result += stack.pop();
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
if (stack.top() == '(') {
result = "Invalid";
}
result += stack.pop();
}
queue.enqueue(result);
return queue;
}
Above is my code for converting infix to postfix. The example i used is "4+2" and what i got is:
Pushed: 43
Popped: 43
Enqueued: 4243
i dont know why it automatically converted "+" to 43, but i want to store the operator as the operator like "+" in the queue. Is it possible? Or is there an error? because i cant find out what the error is. thank you

Check if string have pair brackets closed with properly order [duplicate]

I am trying to create a program that takes a string as an argument into its constructor. I need a method that checks whether the string is a balanced parenthesized expression. It needs to handle ( { [ ] } ) each open needs to balance with its corresponding closing bracket. For example a user could input [({})] which would be balanced and }{ would be unbalanced. This doesn't need to handle letters or numbers. I need to use a stack to do this.
I was given this pseudocode but can not figure how to implement it in java. Any advice would be awesome.
Update- sorry forgot to post what i had so far. Its all messed up because at first i was trying to use char and then i tried an array.. im not exactly sure where to go.
import java.util.*;
public class Expression
{
Scanner in = new Scanner(System.in);
Stack<Integer> stack = new Stack<Integer>();
public boolean check()
{
System.out.println("Please enter your expression.");
String newExp = in.next();
String[] exp = new String[newExp];
for (int i = 0; i < size; i++)
{
char ch = exp.charAt(i);
if (ch == '(' || ch == '[' || ch == '{')
stack.push(i);
else if (ch == ')'|| ch == ']' || ch == '}')
{
//nothing to match with
if(stack.isEmpty())
{
return false;
}
else if(stack.pop() != ch)
{
return false;
}
}
}
if (stack.isEmpty())
{
return true;
}
else
{
return false;
}
}
}
I hope this code can help:
import java.util.Stack;
public class BalancedParenthensies {
public static void main(String args[]) {
System.out.println(balancedParenthensies("{(a,b)}"));
System.out.println(balancedParenthensies("{(a},b)"));
System.out.println(balancedParenthensies("{)(a,b}"));
}
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);
} 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();
}
}
public static boolean isBalanced(String expression) {
if ((expression.length() % 2) == 1) return false;
else {
Stack<Character> s = new Stack<>();
for (char bracket : expression.toCharArray())
switch (bracket) {
case '{': s.push('}'); break;
case '(': s.push(')'); break;
case '[': s.push(']'); break;
default :
if (s.isEmpty() || bracket != s.peek()) { return false;}
s.pop();
}
return s.isEmpty();
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String expression = in.nextLine();
boolean answer = isBalanced(expression);
if (answer) { System.out.println("YES");}
else { System.out.println("NO");}
}
The pseudo code equivalent java implementation of the algorithm is java is as follows.
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* #author Yogen Rai
*/
public class BalancedBraces
{
public static void main(String[] args) {
System.out.println(isBalanced("{{}}") ? "YES" : "NO"); // YES
System.out.println(isBalanced("{{}(") ? "YES" : "NO"); // NO
System.out.println(isBalanced("{()}") ? "YES" : "NO"); // YES
System.out.println(isBalanced("}{{}}") ? "YES" : "NO"); // NO
}
public static boolean isBalanced(String brackets) {
// set matching pairs
Map<Character, Character> braces = new HashMap<>();
braces.put('(', ')');
braces.put('[',']');
braces.put('{','}');
// if length of string is odd, then it is not balanced
if (brackets.length() % 2 != 0) {
return false;
}
// travel half until openings are found and compare with
// remaining if the closings matches
Stack<Character> halfBraces = new Stack();
for(char ch: brackets.toCharArray()) {
if (braces.containsKey(ch)) {
halfBraces.push(braces.get(ch));
}
// if stack is empty or if closing bracket is not equal to top of stack,
// then braces are not balanced
else if(halfBraces.isEmpty() || ch != halfBraces.pop()) {
return false;
}
}
return halfBraces.isEmpty();
}
}
It's important to use a stack to push opening symbols onto it, then when you come across a closing brace you pop the element off the top of the stack and then you check it to see if it matches the type of closing brace. Here is a java implementation.
import java.util.Stack;
public class Balanced {
public static void main (String [] args)
{
String test_good = "()(){}{}{()}";
String test_bad = "((({}{}))()";
System.out.println(checkBalanced(test_good));
System.out.println(checkBalanced(test_bad));
}
public static boolean checkBalanced(String check)
{
Stack<Character> S = new Stack<Character>();
for(int a = 0; a < check.length(); a++)
{
char let = check.charAt(a);
if(let == '[' || let == '{' || let == '(')
S.push(let);
else if(let == ']' || let == '}' || let == ')')
{
if(S.empty())
return false;
switch(let)
{
// Opening square brace
case ']':
if (S.pop() != '[')
return false;
break;
// Opening curly brace
case '}':
if (S.pop() != '{')
return false;
break;
// Opening paren brace
case ')':
if (S.pop() != '(')
return false;
break;
default:
break;
}
}
}
if(S.empty())
return true;
return false;
}
}
Do you mind, if I will add my freaky-style solution based on JavaScript?
It's an ad-hoc stuff, not for production, but for the interviews or something like that. Or just for fun.
The code:
function reduceStr (str) {
const newStr = str.replace('()', '').replace('{}', '').replace('[]', '')
if (newStr !== str) return reduceStr(newStr)
return newStr
}
function verifyNesting (str) {
return reduceStr(str).length === 0
}
Checks:
console.log(verifyNesting('[{{[(){}]}}[]{}{{(())}}]')) //correct
console.log(verifyNesting('[{{[(){}]}}[]{}{({())}}]')) //incorrect
Explanation:
It will recursively remove closes pairs "()", "[]" and "{}":
'[{{[(){}]}}[]{}{{(())}}]'
'[{{}}[]{}{{(())}}]'
'[{}{}{{()}}]'
'[{}{{}}]'
'[{{}}]'
'[{}]'
''
If at the end string's length will be empty - it's true, if not - it's false.
P.S. Few answers
Why not for production?
Because it's slow, and don't care about the possibility of some other characters between pairs.
Why JS? We love Java
Because I'm a frontend developer but met the same task, so perhaps it can be useful for somebody. And JS is also JVM lang =)
But why...
Because all JS developers are crazy, that's why.
This is my own implementation. I tried to make it the shortest an clearest way possible:
public static boolean isBraceBalanced(String braces) {
Stack<Character> stack = new Stack<Character>();
for(char c : braces.toCharArray()) {
if(c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if((c == ')' && (stack.isEmpty() || stack.pop() != '(')) ||
(c == ']' && (stack.isEmpty() || stack.pop() != '[')) ||
(c == '}' && (stack.isEmpty() || stack.pop() != '{'))) {
return false;
}
}
return stack.isEmpty();
}
You are pushing i - the index - on the stack, and comparing against ch. You should push and pop ch.
Please try this.
import java.util.Stack;
public class PatternMatcher {
static String[] patterns = { "{([])}", "{}[]()", "(}{}]]", "{()", "{}" };
static String openItems = "{([";
boolean isOpen(String sy) {
return openItems.contains(sy);
}
String getOpenSymbol(String byCloseSymbol) {
switch (byCloseSymbol) {
case "}":
return "{";
case "]":
return "[";
case ")":
return "(";
default:
return null;
}
}
boolean isValid(String pattern) {
if(pattern == null) {
return false;
}
Stack<String> stack = new Stack<String>();
char[] symbols = pattern.toCharArray();
if (symbols.length == 0 || symbols.length % 2 != 0) {
return false;
}
for (char c : symbols) {
String symbol = Character.toString(c);
if (isOpen(symbol)) {
stack.push(symbol);
} else {
String openSymbol = getOpenSymbol(symbol);
if (stack.isEmpty()
|| openSymbol == null
|| !openSymbol.equals(stack.pop())) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
PatternMatcher patternMatcher = new PatternMatcher();
for (String pattern : patterns) {
boolean valid = patternMatcher.isValid(pattern);
System.out.println(pattern + "\t" + valid);
}
}
}
Using switch-case for better readability and handling of other scenarios:
import java.util.Scanner;
import java.util.Stack;
public class JavaStack
{
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input = sc.next();
System.out.println(isStringBalanced(input));
}
scanner.close();
}
private static boolean isStringBalanced(String testString)
{
Stack<Character> stack = new Stack<Character>();
for (char c : testString.toCharArray()) {
switch (c) {
case '[':
case '(':
case '{':
stack.push(c);
break;
case ']':
if (stack.isEmpty() || stack.pop() != '[') {
return false;
}
break;
case ')':
if (stack.isEmpty() || stack.pop() != '(') {
return false;
}
break;
case '}':
if (stack.isEmpty() || stack.pop() != '{') {
return false;
}
break;
default:
break;
}
}
// stack has to be empty, if not, the balance was wrong
return stack.empty();
}
}
This is my implementation for this question. This program allows numbers, alphabets and special characters with input string but simply ignore them while processing the string.
CODE:
import java.util.Scanner;
import java.util.Stack;
public class StringCheck {
public static void main(String[] args) {
boolean flag =false;
Stack<Character> input = new Stack<Character>();
System.out.println("Enter your String to check:");
Scanner scanner = new Scanner(System.in);
String sinput = scanner.nextLine();
char[] c = new char[15];
c = sinput.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '{' || c[i] == '(' || c[i] == '[')
input.push(c[i]);
else if (c[i] == ']') {
if (input.pop() == '[') {
flag = true;
continue;
} else {
flag = false;
break;
}
} else if (c[i] == ')') {
if (input.pop() == '(') {
flag = true;
continue;
} else {
flag = false;
break;
}
} else if (c[i] == '}') {
if (input.pop() == '{') {
flag = true;
continue;
} else {
flag = false;
break;
}
}
}
if (flag == true)
System.out.println("Valid String");
else
System.out.println("Invalid String");
scanner.close();
}
}
Similar to one of the code above in JAVA but It needs one more else statement added in order to avoid stack comparison with characters other than braces :
else if(bracketPair.containsValue(strExpression.charAt(i)))
public boolean isBalanced(String strExpression){
Map<Character,Character> bracketPair = new HashMap<Character,Character>();
bracketPair.put('(', ')');
bracketPair.put('[', ']');
bracketPair.put('{', '}');
Stack<Character> stk = new Stack<Character>();
for(int i =0;i<strExpression.length();i++){
if(bracketPair.containsKey(strExpression.charAt(i)))
stk.push(strExpression.charAt(i));
else if(bracketPair.containsValue(strExpression.charAt(i)))
if(stk.isEmpty()||bracketPair.get(stk.pop())!=strExpression.charAt(i))
return false;
}
if(stk.isEmpty())
return true;
else
return false;
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class BalancedParenthesisWithStack {
/*This is purely Java Stack based solutions without using additonal
data structure like array/Map */
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
/*Take list of String inputs (parenthesis expressions both valid and
invalid from console*/
List<String> inputs=new ArrayList<>();
while (sc.hasNext()) {
String input=sc.next();
inputs.add(input);
}
//For every input in above list display whether it is valid or
//invalid parenthesis expression
for(String input:inputs){
System.out.println("\nisBalancedParenthesis:"+isBalancedParenthesis
(input));
}
}
//This method identifies whether expression is valid parenthesis or not
public static boolean isBalancedParenthesis(String expression){
//sequence of opening parenthesis according to its precedence
//i.e. '[' has higher precedence than '{' or '('
String openingParenthesis="[{(";
//sequence of closing parenthesis according to its precedence
String closingParenthesis=")}]";
//Stack will be pushed on opening parenthesis and popped on closing.
Stack<Character> parenthesisStack=new Stack<>();
/*For expression to be valid :
CHECK :
1. it must start with opening parenthesis [()...
2. precedence of parenthesis should be proper (eg. "{[" invalid
"[{(" valid )
3. matching pair if( '(' => ')') i.e. [{()}(())] ->valid [{)]not
*/
if(closingParenthesis.contains
(((Character)expression.charAt(0)).toString())){
return false;
}else{
for(int i=0;i<expression.length();i++){
char ch= (Character)expression.charAt(i);
//if parenthesis is opening(ie any of '[','{','(') push on stack
if(openingParenthesis.contains(ch.toString())){
parenthesisStack.push(ch);
}else if(closingParenthesis.contains(ch.toString())){
//if parenthesis is closing (ie any of ']','}',')') pop stack
//depending upon check-3
if(parenthesisStack.peek()=='(' && (ch==')') ||
parenthesisStack.peek()=='{' && (ch=='}') ||
parenthesisStack.peek()=='[' && (ch==']')
){
parenthesisStack.pop();
}
}
}
return (parenthesisStack.isEmpty())? true : false;
}
}
An alternative to Hashmap and an efficient way would be to use a Deque:
public boolean isValid(String s)
{
if(s == null || s.length() == 0)
return true;
Deque<Character> stack = new ArrayDeque<Character>();
for(char c : s.toCharArray())
{
if(c == '{')
stack.addFirst('}');
else if(c == '(')
stack.addFirst(')');
else if(c == '[')
stack .addFirst(']');
else if(stack.isEmpty() || c != stack.removeFirst())
return false;
}
return stack.isEmpty();
}
Late Post.
package com.prac.stack;
public class BalanceBrackets {
public static void main(String[] args) {
String str = "{()}[]";
char a[] = str.toCharArray();
System.out.println(check(a));
}
static boolean check(char[] t) {
Stackk st = new Stackk();
for (int i = 0; i < t.length; i++) {
if (t[i] == '{' || t[i] == '(' || t[i] == '[') {
st.push(t[i]);
}
if (t[i] == '}' || t[i] == ')' || t[i] == ']') {
if (st.isEmpty()) {
return false;
} else if (!isMatching(st.pop(), t[i])) {
return false;
}
}
}
if (st.isEmpty()) {
return true;
} else {
return false;
}
}
static boolean isMatching(char a, char b) {
if (a == '(' && b == ')') {
return true;
} else if (a == '{' && b == '}') {
return true;
} else if (a == '[' && b == ']') {
return true;
} else {
return false;
}
}
}
public static void main(String[] args) {
String exp = "{[()()]()}";
if(isBalanced(exp)){
System.out.println("Balanced");
}else{
System.out.println("Not Balanced");
}
}
public static boolean isBalanced(String exp){
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < exp.length(); i++) {
char a = exp.charAt(i);
char b =' ';
if(!stack.isEmpty()){
b = stack.peek();
}
if(a == '(' || a == '[' || a == '{'){
stack.push(a);
continue;
}
else if((b == '(' && a == ')') || (b == '[' && a == ']') || (b == '{' && a == '}')){
stack.pop();
continue;
}
else{
return false;
}
}
return stack.isEmpty();
}
Stack is always most preferable data structure in this case, you can try this by considering time and space complexity.
This code works for all cases include other chars not only parentheses
ex:
Please enter input
{ibrahim[k]}
true
()[]{}[][]
true
saddsd]
false
public class Solution {
private static Map<Character, Character> parenthesesMapLeft = new HashMap<>();
private static Map<Character, Character> parenthesesMapRight = new HashMap<>();
static {
parenthesesMapLeft.put('(', '(');
parenthesesMapRight.put(')', '(');
parenthesesMapLeft.put('[', '[');
parenthesesMapRight.put(']', '[');
parenthesesMapLeft.put('{', '{');
parenthesesMapRight.put('}', '{');
}
public static void main(String[] args) {
System.out.println("Please enter input");
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
System.out.println(isBalanced(str));
}
public static boolean isBalanced(String str) {
boolean result = false;
if (str.length() < 2)
return false;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (!parenthesesMapRight.containsKey(ch) && !parenthesesMapLeft.containsKey(ch)) {
continue;
}
if (parenthesesMapLeft.containsKey(ch)) {
stack.push(ch);
} else {
if (!stack.isEmpty() && stack.pop() == parenthesesMapRight.get(ch).charValue()) {
result = true;
} else {
return false;
}
}
}
if (!stack.isEmpty())
return result = false;
return result;
}
}
import java.util.Stack;
public class StackParenthesisImplementation {
public static void main(String[] args) {
String Parenthesis = "[({})]";
char[] charParenthesis = Parenthesis.toCharArray();
boolean evalParanthesisValue = evalParanthesis(charParenthesis);
if(evalParanthesisValue == true)
System.out.println("Brackets are good");
else
System.out.println("Brackets are not good");
}
static boolean evalParanthesis(char[] brackets)
{
boolean IsBracesOk = false;
boolean PairCount = false;
Stack<Character> stack = new Stack<Character>();
for(char brace : brackets)
{
if(brace == '(' || brace == '{' || brace == '['){
stack.push(brace);
PairCount = false;
}
else if(!stack.isEmpty())
{
if(brace == ')' || brace == '}' || brace == ']')
{
char CharPop = stack.pop();
if((brace == ')' && CharPop == '('))
{
IsBracesOk = true; PairCount = true;
}
else if((brace == '}') && (CharPop == '{'))
{
IsBracesOk = true; PairCount = true;
}
else if((brace == ']') && (CharPop == '['))
{
IsBracesOk = true; PairCount = true;
}
else
{
IsBracesOk = false;
PairCount = false;
break;
}
}
}
}
if(PairCount == false)
return IsBracesOk = false;
else
return IsBracesOk = true;
}
}
public static void main(String[] args) {
System.out.println("is balanced : "+isBalanced("(){}[]<>"));
System.out.println("is balanced : "+isBalanced("({})[]<>"));
System.out.println("is balanced : "+isBalanced("({[]})<>"));
System.out.println("is balanced : "+isBalanced("({[<>]})"));
System.out.println("is balanced : "+isBalanced("({})[<>]"));
System.out.println("is balanced : "+isBalanced("({[}])[<>]"));
System.out.println("is balanced : "+isBalanced("([{})]"));
System.out.println("is balanced : "+isBalanced("[({}])"));
System.out.println("is balanced : "+isBalanced("[(<{>})]"));
System.out.println("is balanced : "+isBalanced("["));
System.out.println("is balanced : "+isBalanced("]"));
System.out.println("is balanced : "+isBalanced("asdlsa"));
}
private static boolean isBalanced(String brackets){
char[] bracketsArray = brackets.toCharArray();
Stack<Character> stack = new Stack<Character>();
Map<Character, Character> openingClosingMap = initOpeningClosingMap();
for (char bracket : bracketsArray) {
if(openingClosingMap.keySet().contains(bracket)){
stack.push(bracket);
}else if(openingClosingMap.values().contains(bracket)){
if(stack.isEmpty() || openingClosingMap.get(stack.pop())!=bracket){
return false;
}
}else{
System.out.println("Only < > ( ) { } [ ] brackets are allowed .");
return false;
}
}
return stack.isEmpty();
}
private static Map<Character, Character> initOpeningClosingMap() {
Map<Character, Character> openingClosingMap = new HashMap<Character, Character>();
openingClosingMap.put(Character.valueOf('('), Character.valueOf(')'));
openingClosingMap.put(Character.valueOf('{'), Character.valueOf('}'));
openingClosingMap.put(Character.valueOf('['), Character.valueOf(']'));
openingClosingMap.put(Character.valueOf('<'), Character.valueOf('>'));
return openingClosingMap;
}
Simplifying and making readable.
Using One Map only and minimum conditions to get desired result.
How about this one, it uses both concept of stack plus counter checks:
import java.util.*;
class Solution{
public static void main(String []argh)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input=sc.next();
Stack<Character> stk = new Stack<Character>();
char[] chr = input.toCharArray();
int ctrl = 0, ctrr = 0;
if(input.length()==0){
System.out.println("true");
}
for(int i=0; i<input.length(); i++){
if(chr[i]=='{'||chr[i]=='('||chr[i]=='['){
ctrl++;
stk.push(chr[i]);
//System.out.println(stk);
}
}
for(int i=0; i<input.length(); i++){
if(chr[i]=='}'||chr[i]==')'||chr[i]==']'){
ctrr++;
if(!stk.isEmpty())
stk.pop();
//System.out.println(stk);
}
}
//System.out.println(stk);
if(stk.isEmpty()&&ctrl==ctrr)
System.out.println("true");
else
System.out.println("false");
}
}
}
This can be used. Passes all the tests.
static String isBalanced(String s) {
if(null == s){
return "";
}
Stack<Character> bracketStack = new Stack<>();
int length = s.length();
if(length < 2 || length > 1000){
return "NO";
}
for(int i = 0; i < length; i++){
Character c= s.charAt(i);
if(c == '(' || c == '{' || c == '[' ){
bracketStack.push(c);
} else {
if(!bracketStack.isEmpty()){
char cPop = bracketStack.pop();
if(c == ']' && cPop!= '['){
return "NO";
}
if(c == ')' && cPop!= '('){
return "NO";
}
if(c == '}' && cPop!= '{'){
return "NO";
}
} else{
return "NO";
}
}
}
if(bracketStack.isEmpty()){
return "YES";
} else {
return "NO";
}
}
Please try this I checked it. It works correctly
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class CloseBrackets {
private static Map<Character, Character> leftChar = new HashMap<>();
private static Map<Character, Character> rightChar = new HashMap<>();
static {
leftChar.put('(', '(');
rightChar.put(')', '(');
leftChar.put('[', '[');
rightChar.put(']', '[');
leftChar.put('{', '{');
rightChar.put('}', '{');
}
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String st = bf.readLine();
System.out.println(isBalanced(st));
}
public static boolean isBalanced(String str) {
boolean result = false;
if (str.length() < 2)
return false;
Stack<Character> stack = new Stack<>();
/* For Example I gave input
* str = "{()[]}"
*/
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (!rightChar.containsKey(ch) && !leftChar.containsKey(ch)) {
continue;
}
// Left bracket only add to stack. Other wise it will goes to else case
// For both above input how value added in stack
// "{(" after close bracket go to else case
if (leftChar.containsKey(ch)) {
stack.push(ch);
} else {
if (!stack.isEmpty()) {
// For both input how it performs
// 3rd character is close bracket so it will pop . pop value is "(" and map value for ")" key will "(" . So both are same .
// it will return true.
// now stack will contain only "{" , and travers to next up to end.
if (stack.pop() == rightChar.get(ch).charValue() || stack.isEmpty()) {
result = true;
} else {
return false;
}
} else {
return false;
}
}
}
if (!stack.isEmpty())
return result = false;
return result;
}
}
Using node reference we can check easily
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CloseBracketsBalance {
private static final Map<String, String> closeBracket= new HashMap<>();
private static final List<String> allBrac = new ArrayList<>();
static {
allBrac.add("[");
allBrac.add("]");
allBrac.add("{");
allBrac.add("}");
allBrac.add("(");
allBrac.add(")");
closeBracket.put("]", "[");
closeBracket.put("}", "{");
closeBracket.put(")", "(");
}
public static void main(String[] args) {
System.out.println(checkSheetIsbalance("[{}({[]{}(dsfd)})]")); // return true
System.out.println(checkSheetIsbalance("[{}({[]{}(dsfd}))]")); // return false
}
public static boolean checkSheetIsbalance(String c) {
char[] charArr = c.toCharArray();
Node node = null;
for(int i=0,j=charArr.length;i<j;i++) {
String ch = charArr[i]+"";
if(!allBrac.contains(ch)) {
continue;
}
if(closeBracket.containsKey(ch)) {
// node close bracket
if(node == null) {
return false;
}
if(!(node.nodeElement).equals(closeBracket.get(ch))) {
return false;
}
node = node.parent;
} else {
//make node for open bracket
node = new Node(ch, node);
}
}
if(node != null) {
return false;
}
return true;
}
}
class Node {
public String nodeElement;
public Node parent;
public Node(String el, Node p) {
this.nodeElement = el;
this.parent = p;
}
}
The improved method, from #Smartoop.
public boolean balancedParenthensies(String str) {
List<Character> leftKeys = Arrays.asList('{', '(', '<', '[');
List<Character> rightKeys = Arrays.asList('}', ')', '>', ']');
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (leftKeys.contains(c)) {
stack.push(c);
} else if (rightKeys.contains(c)) {
int index = rightKeys.indexOf(c);
if (stack.isEmpty() || stack.pop() != leftKeys.get(index)) {
return false;
}
}
}
return stack.isEmpty();
}
Considering string consists only of '(' ')' '{' '}' '[' ']'. Here is a code method that returns true or false based on whether equation is balanced or not.
private static boolean checkEquation(String input) {
List<Character> charList = new ArrayList<Character>();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '(' || input.charAt(i) == '{' || input.charAt(i) == '[') {
charList.add(input.charAt(i));
} else if ((input.charAt(i) == ')' && charList.get(charList.size() - 1) == '(')
|| (input.charAt(i) == '}' && charList.get(charList.size() - 1) == '{')
|| (input.charAt(i) == ']' && charList.get(charList.size() - 1) == '[')) {
charList.remove(charList.size() - 1);
} else
return false;
}
if(charList.isEmpty())
return true;
else
return false;
}
///check Parenthesis
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()){
if(map.containsKey(c)){
stack.push(c);
} else if(!stack.empty() && map.get(stack.peek())==c){
stack.pop();
} else {
return false;
}
}
return stack.empty();
}
public void validateExpression(){
if(!str.isEmpty() && str != null){
if( !str.trim().equals("(") && !str.trim().equals(")")){
char[] chars = str.toCharArray();
for(char c: chars){
if(!Character.isLetterOrDigit(c) && c == '(' || c == ')') {
charList.add(c);
}
}
for(Character ele: charList){
if(operatorMap.get(ele) != null && operatorMap.get(ele) != 0){
operatorMap.put(ele,operatorMap.get(ele)+1);
}else{
operatorMap.put(ele,1);
}
}
for(Map.Entry<Character, Integer> ele: operatorMap.entrySet()){
System.out.println(String.format("Brace Type \"%s\" and count is \"%d\" ", ele.getKey(),ele.getValue()));
}
if(operatorMap.get('(') == operatorMap.get(')')){
System.out.println("**** Valid Expression ****");
}else{
System.out.println("**** Invalid Expression ****");
}
}else{
System.out.println("**** Incomplete expression to validate ****");
}
}else{
System.out.println("**** Expression is empty or null ****");
}
}
Here is the Code. I have tested all the possible test case on Hacker Rank.
static String isBalanced(String input) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < input.length(); i++) {
Character ch = input.charAt(i);
if (input.charAt(i) == '{' || input.charAt(i) == '['
|| input.charAt(i) == '(') {
stack.push(input.charAt(i));
} else {
if (stack.isEmpty()
|| (stack.peek() == '[' && ch != ']')
|| (stack.peek() == '{' && ch != '}')
|| (stack.peek() == '(' && ch != ')')) {
return "NO";
} else {
stack.pop();
}
}
}
if (stack.empty())
return "YES";
return "NO";
}
import java.util.Objects;
import java.util.Stack;
public class BalanceBrackets {
public static void main(String[] args) {
String input="(a{[d]}b)";
System.out.println(isBalance(input)); ;
}
private static boolean isBalance(String input) {
Stack <Character> stackFixLength = new Stack();
if(input == null || input.length() < 2) {
throw new IllegalArgumentException("in-valid arguments");
}
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '(' || input.charAt(i) == '{' || input.charAt(i) == '[') {
stackFixLength.push(input.charAt(i));
}
if (input.charAt(i) == ')' || input.charAt(i) == '}' || input.charAt(i) == ']') {
if(stackFixLength.empty()) return false;
char b = stackFixLength.pop();
if (input.charAt(i) == ')' && b == '(' || input.charAt(i) == '}' && b == '{' || input.charAt(i) == ']' && b == '[') {
continue;
} else {
return false;
}
}
}
return stackFixLength.isEmpty();
}
}
package Stack;
import java.util.Stack;
public class BalancingParenthesis {
boolean isBalanced(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
stack.push(s.charAt(i)); // push to the stack
}
if (s.charAt(i) == ')' || s.charAt(i) == '}' || s.charAt(i) == ']') {
if (stack.isEmpty()) {
return false; // return false as there is nothing to match
}
Character top = stack.pop(); // to get the top element in the stack
if (top == '(' && s.charAt(i) != ')' || top == '{' && s.charAt(i) != '}'
|| top == '[' && s.charAt(i) != ']') {
return false;
}
}
}
if (stack.isEmpty()) {
return true; // check if every symbol is matched
}
return false; // if some symbols were unmatched
}
public static void main(String[] args) {
BalancingParenthesis obj = new BalancingParenthesis();
System.out.println(obj.isBalanced("()[]{}[][]"));
}
}
// Time Complexity : O(n)
Code snippet for implementing matching parenthesis using java.util.Stack data structure -
//map for storing matching parenthesis pairs
private static final Map<Character, Character> matchingParenMap = new HashMap<>();
//set for storing opening parenthesis
private static final Set<Character> openingParenSet = new HashSet<>();
static {
matchingParenMap.put(')','(');
matchingParenMap.put(']','[');
matchingParenMap.put('}','{');
openingParenSet.addAll(matchingParenMap.values());
}
//check if parenthesis match
public static boolean hasMatchingParen(String input) {
try {
//stack to store opening parenthesis
Stack<Character> parenStack = new Stack<>();
for(int i=0; i< input.length(); i++) {
char ch = input.charAt(i);
//if an opening parenthesis then push to the stack
if(openingParenSet.contains(ch)) {
parenStack.push(ch);
}
//for closing parenthesis
if(matchingParenMap.containsKey(ch)) {
Character lastParen = parenStack.pop();
if(lastParen != matchingParenMap.get(ch)) {
return false;
}
}
}
//returns true if the stack is empty else false
return parenStack.isEmpty();
}
catch(StackOverflowException s) {}
catch(StackUnderflowException s1) {}
return false;
}
I have explained the code snippet and the algorithm used on blog http://hetalrachh.home.blog/2019/12/25/stack-data-structure/

How to simplify my methods with tons of if statements [duplicate]

This question already has answers here:
Read a text file and store every single character occurrence
(3 answers)
Closed 6 years ago.
My code is supposed to read an input file and count the uses of each character in the file then print them all out. The code works but I know that there has to be a way to cut down on all the if statements. Right now I'm making methods for reading and one for output so its not all written in my main method. Any and all suggestions are helpful, thanks.
import java.io.FileReader;
import java.io.IOException;
public class CharacterCounts {
static int nl = 0;
static int sp = 0;
static int ex = 0;
static int ap = 0;
static int cm = 0;
static int hy = 0;
static int pd = 0;
static int cn = 0;
static int sm = 0;
static int qu = 0;
static int a = 0;
static int b = 0;
static int c = 0;
static int d = 0;
static int e = 0;
static int f = 0;
static int g = 0;
static int h = 0;
static int ii = 0;
static int j = 0;
static int k = 0;
static int l = 0;
static int m = 0;
static int n = 0;
static int o = 0;
static int p = 0;
static int q = 0;
static int r = 0;
static int s = 0;
static int t = 0;
static int u = 0;
static int v = 0;
static int w = 0;
static int x = 0;
static int y = 0;
static int z = 0;
static int A = 0;
static int B = 0;
static int C = 0;
static int D = 0;
static int E = 0;
static int F = 0;
static int G = 0;
static int H = 0;
static int I = 0;
static int J = 0;
static int K = 0;
static int L = 0;
static int M = 0;
static int N = 0;
static int O = 0;
static int P = 0;
static int Q = 0;
static int R = 0;
static int S = 0;
static int T = 0;
static int U = 0;
static int V = 0;
static int W = 0;
static int X = 0;
static int Y = 0;
static int Z = 0;
public static void main(String args[]) throws IOException {
String file = args[0];
#SuppressWarnings("resource")
FileReader scanner = new FileReader(file);
int i;
while ((i = scanner.read()) != -1) {
if ((char) i == '\n') {
nl++;
} else if ((char) i == ' ') {
sp++;
} else if ((char) i == '!') {
ex++;
} else if ((char) i == '\'') {
ap++;
} else if ((char) i == ',') {
cm++;
} else if ((char) i == '-') {
hy++;
} else if ((char) i == '.') {
pd++;
} else if ((char) i == ':') {
cn++;
} else if ((char) i == ';') {
sm++;
} else if ((char) i == '?') {
qu++;
} else if ((char) i == 'a') {
a++;
} else if ((char) i == 'b') {
b++;
} else if ((char) i == 'c') {
c++;
} else if ((char) i == 'd') {
d++;
} else if ((char) i == 'e') {
e++;
} else if ((char) i == 'f') {
f++;
} else if ((char) i == 'g') {
g++;
} else if ((char) i == 'h') {
h++;
} else if ((char) i == 'i') {
ii++;
} else if ((char) i == 'j') {
j++;
} else if ((char) i == 'k') {
k++;
} else if ((char) i == 'l') {
l++;
} else if ((char) i == 'm') {
m++;
} else if ((char) i == 'n') {
n++;
} else if ((char) i == 'o') {
o++;
} else if ((char) i == 'p') {
p++;
} else if ((char) i == 'q') {
q++;
} else if ((char) i == 'r') {
r++;
} else if ((char) i == 's') {
s++;
} else if ((char) i == 't') {
t++;
} else if ((char) i == 'u') {
u++;
} else if ((char) i == 'v') {
v++;
} else if ((char) i == 'w') {
w++;
} else if ((char) i == 'x') {
x++;
} else if ((char) i == 'y') {
y++;
} else if ((char) i == 'z') {
z++;
} else if ((char) i == 'A') {
A++;
} else if ((char) i == 'B') {
B++;
} else if ((char) i == 'C') {
C++;
} else if ((char) i == 'D') {
D++;
} else if ((char) i == 'E') {
E++;
} else if ((char) i == 'F') {
F++;
} else if ((char) i == 'G') {
G++;
} else if ((char) i == 'H') {
H++;
} else if ((char) i == 'I') {
I++;
} else if ((char) i == 'J') {
J++;
} else if ((char) i == 'K') {
K++;
} else if ((char) i == 'L') {
L++;
} else if ((char) i == 'M') {
M++;
} else if ((char) i == 'N') {
N++;
} else if ((char) i == 'O') {
O++;
} else if ((char) i == 'P') {
P++;
} else if ((char) i == 'Q') {
Q++;
} else if ((char) i == 'R') {
R++;
} else if ((char) i == 'S') {
S++;
} else if ((char) i == 'T') {
T++;
} else if ((char) i == 'U') {
U++;
} else if ((char) i == 'V') {
V++;
} else if ((char) i == 'W') {
W++;
} else if ((char) i == 'X') {
X++;
} else if ((char) i == 'Y') {
Y++;
} else if ((char) i == 'Z') {
Z++;
}
}
if (nl != 0) {
System.out.printf("'/n' %d\n", nl);
}
if (sp != 0) {
System.out.printf("' ' %d\n", sp);
}
if (ex != 0) {
System.out.printf("'!' %d\n", ex);
}
if (ap != 0) {
System.out.printf("''' %d\n", ap);
}
if (cm != 0) {
System.out.printf("',' %d\n", cm);
}
if (hy != 0) {
System.out.printf("'-' %d\n", hy);
}
if (pd != 0) {
System.out.printf("'.' %d\n", pd);
}
if (cn != 0) {
System.out.printf("':' %d\n", cn);
}
if (sm != 0) {
System.out.printf("';' %d\n", sm);
}
if (qu != 0) {
System.out.printf("'?' %d\n", qu);
}
if (A != 0) {
System.out.printf("'A' %d\n", A);
}
if (B != 0) {
System.out.printf("'B' %d\n", B);
}
if (C != 0) {
System.out.printf("'C' %d\n", C);
}
if (D != 0) {
System.out.printf("'D' %d\n", D);
}
if (E != 0) {
System.out.printf("'E' %d\n", E);
}
if (F != 0) {
System.out.printf("'F' %d\n", F);
}
if (G != 0) {
System.out.printf("'G' %d\n", G);
}
if (H != 0) {
System.out.printf("'H' %d\n", H);
}
if (I != 0) {
System.out.printf("'I' %d\n", I);
}
if (J != 0) {
System.out.printf("'J' %d\n", J);
}
if (K != 0) {
System.out.printf("'K' %d\n", K);
}
if (L != 0) {
System.out.printf("'L' %d\n", L);
}
if (M != 0) {
System.out.printf("'M' %d\n", M);
}
if (N != 0) {
System.out.printf("'N' %d\n", N);
}
if (O != 0) {
System.out.printf("'O' %d\n", O);
}
if (P != 0) {
System.out.printf("'P' %d\n", P);
}
if (Q != 0) {
System.out.printf("'Q' %d\n", Q);
}
if (R != 0) {
System.out.printf("'R' %d\n", R);
}
if (S != 0) {
System.out.printf("'S' %d\n", S);
}
if (T != 0) {
System.out.printf("'T' %d\n", T);
}
if (U != 0) {
System.out.printf("'U' %d\n", U);
}
if (V != 0) {
System.out.printf("'V' %d\n", V);
}
if (W != 0) {
System.out.printf("'W' %d\n", W);
}
if (X != 0) {
System.out.printf("'X' %d\n", X);
}
if (Y != 0) {
System.out.printf("'Y' %d\n", Y);
}
if (Z != 0) {
System.out.printf("'Z' %d\n", Z);
}
if (a != 0) {
System.out.printf("'a' %d\n", a);
}
if (b != 0) {
System.out.printf("'b' %d\n", b);
}
if (c != 0) {
System.out.printf("'c' %d\n", c);
}
if (d != 0) {
System.out.printf("'d' %d\n", d);
}
if (e != 0) {
System.out.printf("'e' %d\n", e);
}
if (f != 0) {
System.out.printf("'f' %d\n", f);
}
if (g != 0) {
System.out.printf("'g' %d\n", g);
}
if (h != 0) {
System.out.printf("'h' %d\n", h);
}
if (ii != 0) {
System.out.printf("'i' %d\n", ii);
}
if (j != 0) {
System.out.printf("'j' %d\n", j);
}
if (k != 0) {
System.out.printf("'k' %d\n", k);
}
if (l != 0) {
System.out.printf("'l' %d\n", l);
}
if (m != 0) {
System.out.printf("'m' %d\n", m);
}
if (n != 0) {
System.out.printf("'n' %d\n", n);
}
if (o != 0) {
System.out.printf("'o' %d\n", o);
}
if (p != 0) {
System.out.printf("'p' %d\n", p);
}
if (q != 0) {
System.out.printf("'q' %d\n", q);
}
if (r != 0) {
System.out.printf("'r' %d\n", r);
}
if (s != 0) {
System.out.printf("'s' %d\n", s);
}
if (t != 0) {
System.out.printf("'t' %d\n", t);
}
if (u != 0) {
System.out.printf("'u' %d\n", u);
}
if (v != 0) {
System.out.printf("'v' %d\n", v);
}
if (w != 0) {
System.out.printf("'w' %d\n", w);
}
if (x != 0) {
System.out.printf("'x' %d\n", x);
}
if (y != 0) {
System.out.printf("'y' %d\n", y);
}
if (z != 0) {
System.out.printf("'z' %d\n", z);
}
}
}
This can be easily improved by using a Map<Character, Integer>. Change your declaration to this:
static final Map<Character, Integer> VALUES = new HashMap<>();
Then the body of your code can be changed to this:
Integer val = VALUES.get(i);
if(val == null) VALUES.put(i, 1);
else VALUES.put(i, val + 1);
Then simply iterate over it to display the values at the end.
Keeping the order, or restricting it to just those characters, could be done by using a LinkedHashMap and pre-populating all the desired values with zero.
Here's an example of what that would look like:
private static final Map<Character, Integer> VALUES = new LinkedHashMap<>();
static{
for(char c : "\n !\\,-.:;?".toCharArray()){
VALUES.put(c, 0);
}
for(char c = 'a'; c < 'z'; c++){
VALUES.put(c, 0);
}
for(char c = 'A'; c < 'Z'; c++){
VALUES.put(c, 0);
}
}
public static void main(String args[]){
try{
String file = args[0];
FileReader scanner = new FileReader(file);
int i;
while ((i = scanner.read()) != -1) {
Integer val = VALUES.get((char)i);
if(val != null) VALUES.put((char)i, val + 1);
}
for(Map.Entry<Character, Integer> entry : VALUES.entrySet()){
if(entry.getValue() > 0)
System.out.println(entry.getKey() + " " + entry.getValue());
}
} catch(IOException ioe){
ioe.printStackTrace();
}
}
^Untested, but should at least be close.
Now tested, and the numerous bugs have been fixed.
Same behavior, more maintainable, less likely to contain typos, and 10% of the typing.

Infix to postfix digit or letter concatenation

working on a program that converts infix notation to postfix. I have it working for most instances except when character concatenation is required. For example, if I pass in a string of numbers (1002+304) it outputs 1, 0, 0, 2, 3, 0, 4, + instead of 1002, 304, +.
import java.util.*;
public class InfixToPostfix {
private Deque<String> postfix; // Used as a queue of String
private static boolean isOperator(char op)
{
if(op=='+'||op=='-'||op=='*'||op=='/'||op=='^'
||op=='('||op==')')
{
return true;
}
return false;
}
private static boolean lowerEqualPrec(char op1, char op2)
{
boolean flag = false;
if(op1=='+'|| op1=='-')
{
if(op2=='+'||op2=='-'||op2=='*'||op2=='/'||op2=='^')
{
flag= true;
}
}else if(op1=='*' || op1=='/')
{
if(op2=='*'||op2=='/'||op2=='^')
{
flag= true;
}
}else if(op1=='^')
{
flag= false;
}else if(op1=='(')
{
flag= false;
}
return flag;
}
public InfixToPostfix(String infix)
{
for(int i=0; i<infix.length(); i++)
{
if(infix.length() ==0 || infix.charAt(0)==')' ||
infix.charAt(i)=='&' || infix.charAt(infix.length()-1)=='(')
{
throw new IllegalArgumentException();
}
}
postfix = new LinkedList<String>();
Stack<Character> stack = new Stack<Character>();
Character ch;
String digits="";
String letters = "";
for(int i=0; i<infix.length(); i++)
{
ch=infix.charAt(i);
if(ch == ' ')
{
//do nothing
}
if(Character.isDigit(ch))
{
digits=""+ch;
if(i+1 >= infix.length() || !Character.isDigit(infix.charAt(i+1)))
{
digits=digits+"";
}
postfix.add(digits);
}
if(Character.isLetter(ch))
{
letters=ch+"";
postfix.add(letters);
}
if(isOperator(ch))
{
if(ch == ')')
{
if(!stack.isEmpty() && stack.peek() != '(')
{
postfix.add(""+stack.pop());
if(!stack.isEmpty())
{
stack.pop();
}
}
}
else
{
if(!stack.isEmpty() && !lowerEqualPrec(ch, stack.peek()))
{
stack.push(ch);
}
else
{
while(!stack.isEmpty() && lowerEqualPrec(ch, stack.peek()))
{
char pop = stack.pop();
if(ch!='(')
{
postfix.add(pop+"");
}
}
stack.push(ch);
}
}
}
}
while(!stack.isEmpty()&&stack.peek()!='(')
{
postfix.add(stack.pop()+"");
}
System.out.println(postfix);
}
public Iterator<String> iterator()
{
return new PostfixIterator(postfix) ;
}
public static void main(String[] args)
{
InfixToPostfix test = new InfixToPostfix("1002+304");
}
}
For postfixConversion
public static String postfixConversion(String input) {
int i;
String postfix = "";
Stack<Character> stack = new Stack<Character>();
for (i = 0; i < input.length(); i++) {
while (input.charAt(i) == ' ') {
++i;
}
if (Character.isDigit(input.charAt(i))) {
postfix += input.charAt(i);
//if (!Character.isDigit(input.charAt(i+1))) {
postfix += ' ';
//}
}
else if (precedenceLevel(input.charAt(i)) != 0) {
while ((!stack.isEmpty()) && (precedenceLevel(stack.peek()) >= precedenceLevel(input.charAt(i))) && (stack.peek() != '(')) {
postfix += stack.peek();
postfix += ' ';
stack.pop();
}
stack.push(input.charAt(i));
}
else if (input.charAt(i) == '(') {
stack.push(input.charAt(i));
}
else if (input.charAt(i) == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix += stack.peek();
stack.pop();
}
stack.pop();
}
}
while (!stack.isEmpty()) {
postfix += stack.peek();
postfix += ' ';
}
return postfix;
}

Categories

Resources