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");
}
}
Related
I am using Jackson version 2.4.3 for converting my complex Java object into a String object, so below is what I'm getting in output. The output is like below (Fyi - I just printed some part of the output)
"{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
Here is my code (PaymentTnx is a complex Java object)
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
String lpTransactionJSON = mapper.writeValueAsString(paymentTxn);
I don't want to see \ slashes in my JSON string. What do I need to do to get a string like below:
"{"FirstName":"John ","LastName":cena,"salary":7500,"skills":["java","python"]}";
String test = "{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
System.out.println(StringEscapeUtils.unescapeJava(test));
This might help you.
I have not tried Jackson. I just have similar situation.
I used org.apache.commons.text.StringEscapeUtils.unescapeJson but it's not working for malformed JSON format like {\"name\": \"john\"}
So, I used this class. Perfectly working fine.
https://gist.githubusercontent.com/jjfiv/2ac5c081e088779f49aa/raw/8bda15d27c73047621a94359492a5a9433f497b2/JSONUtil.java
// BSD License (http://lemurproject.org/galago-license)
package org.lemurproject.galago.utility.json;
public class JSONUtil {
public static String escape(String input) {
StringBuilder output = new StringBuilder();
for(int i=0; i<input.length(); i++) {
char ch = input.charAt(i);
int chx = (int) ch;
// let's not put any nulls in our strings
assert(chx != 0);
if(ch == '\n') {
output.append("\\n");
} else if(ch == '\t') {
output.append("\\t");
} else if(ch == '\r') {
output.append("\\r");
} else if(ch == '\\') {
output.append("\\\\");
} else if(ch == '"') {
output.append("\\\"");
} else if(ch == '\b') {
output.append("\\b");
} else if(ch == '\f') {
output.append("\\f");
} else if(chx >= 0x10000) {
assert false : "Java stores as u16, so it should never give us a character that's bigger than 2 bytes. It literally can't.";
} else if(chx > 127) {
output.append(String.format("\\u%04x", chx));
} else {
output.append(ch);
}
}
return output.toString();
}
public static String unescape(String input) {
StringBuilder builder = new StringBuilder();
int i = 0;
while (i < input.length()) {
char delimiter = input.charAt(i); i++; // consume letter or backslash
if(delimiter == '\\' && i < input.length()) {
// consume first after backslash
char ch = input.charAt(i); i++;
if(ch == '\\' || ch == '/' || ch == '"' || ch == '\'') {
builder.append(ch);
}
else if(ch == 'n') builder.append('\n');
else if(ch == 'r') builder.append('\r');
else if(ch == 't') builder.append('\t');
else if(ch == 'b') builder.append('\b');
else if(ch == 'f') builder.append('\f');
else if(ch == 'u') {
StringBuilder hex = new StringBuilder();
// expect 4 digits
if (i+4 > input.length()) {
throw new RuntimeException("Not enough unicode digits! ");
}
for (char x : input.substring(i, i + 4).toCharArray()) {
if(!Character.isLetterOrDigit(x)) {
throw new RuntimeException("Bad character in unicode escape.");
}
hex.append(Character.toLowerCase(x));
}
i+=4; // consume those four digits.
int code = Integer.parseInt(hex.toString(), 16);
builder.append((char) code);
} else {
throw new RuntimeException("Illegal escape sequence: \\"+ch);
}
} else { // it's not a backslash, or it's the last character.
builder.append(delimiter);
}
}
return builder.toString();
}
}
With Jackson do:
toString(paymentTxn);
with
public String toString(Object obj) {
try (StringWriter w = new StringWriter();) {
new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true).writeValue(w, obj);
return w.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
This here is not valid JSON:
"{"FirstName":"John ","LastName":cena,"salary":7500,"skills":["java","python"]}";
This here is valid JSON, specifically a single string value:
"{\"FirstName\":\"John \",\"LastName\":cena,\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
Given that you're calling writeValueAsString, this is the correct behaviour. I would suggest writeValue, perhaps?
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!
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;
}
}
}
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.
I'm supposed to create a Java program which reads expressions that contain, among other items, braces { },
brackets [ ], and parentheses ( ). My program should be properly
nested and that ‘(‘ matches ‘)’, ‘[‘ matches ‘]’, and ‘{’ matches ‘}‘ The
program should be terminated by a ‘$’ at the beginning of an input line.
These are supposed to be sample runs of my program:
Enter an Expression:
A[F + X {Y – 2}]
The expression is Legal
Enter an Expression:
B+[3 – {X/2})*19 + 2/(X – 7)
ERROR—‘]’ expected
Enter an Expression:
()) (
ERROR--‘)’ without ‘(‘
$
I created a class called BalancedExpression and a driver called ExpressionChecker.
I completed my BalancedExpression class. But, I'm having trouble setting up my driver to print out an expression using an InputStreamReader and a BufferedReader. The only thing I was able to figure out was how to terminate my program by letting the user enter a $.
Here is my code so far:
Balanced Expression class:
public class BalancedExpression
{
public BalancedExpression() // Default Constructor
{
sp = 0; // the stack pointer
theStack = new int[MAX_STACK_SIZE];
}
public void push(int value) // Method to push an expression into the stack
{
if (!full())
theStack[sp++] = value;
}
public int pop() // Method to pop an expression out of the stack
{
if (!empty())
return theStack[--sp];
else
return -1;
}
public boolean full() // Method to determine if the stack is full
{
if (sp == MAX_STACK_SIZE)
return true;
else
return false;
}
public boolean empty() // Method to determine if the stack is empty
{
if (sp == 0)
return true;
else
return false;
}
public static boolean checkExpression(String ex) // Method to check Expression in stack
{
BalancedExpression stExpression = new BalancedExpression();
for(int i = 0; i< MAX_STACK_SIZE; i++)
{
char ch = ex.charAt(i);
if(ch == '(' || ch == '{' || ch == '[')
stExpression.push(ch);
else if(ch == ')' && !stExpression.empty() && stExpression.equals('('))
stExpression.pop();
else if(ch == '}' && !stExpression.empty() && stExpression.equals('{'))
stExpression.pop();
else if(ch == ']' && !stExpression.empty() && stExpression.equals('['))
stExpression.pop();
else if(ch == ')' || ch == '}' || ch == ']' )
return false;
}
if(!stExpression.empty())
return false;
return true;
}
private int sp;
private int[] theStack;
private static final int MAX_STACK_SIZE = 6;
}// End of class BalancedExpression
My Driver Program:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExpressionChecker
{
public static void main(String[] args)
{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(reader);
BalancedExpression exp = new BalancedExpression();
String expression = "";
do
{
try{
System.out.print("Enter an Expression: ");
expression = console.readLine();
if("$".equals(expression))
break;
}catch(Exception e){
System.out.println("IO error:" + e);
}
}while(!expression.equals(""));// End of while loop
}
}// End of class ExpressionChecker
Can anyone please help me develop my driver program to print out an output similar to the sample example?
Any help is appreciated. Thanks!
In the if statements in checkExpression method you are using
stExpression.equals()
while what you want to do is to 'peek' at the value on the top of the stack.
Adding simple method that pops the value, pushes it back and returns it should solve the problem(at least this part).
Here is a very short example where you can do the above check very easily :) We have Stack class in Java, it will make the program very easy. Please find below the simple code for this question:
package com.test;
import java.util.Scanner;
import java.util.Stack;
public class StackChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enete an expression : ");
String expr = sc.nextLine();
if(checkvalidExpression(expr)){
System.out.println("The Expression '"+expr+"' is a valid expression!!!");
}
else{
System.out.println("The Expression '"+expr+"' is a NOT a valid expression!!!");
}
}
public static boolean checkvalidExpression(String expr){
Stack<Character> charStack = new Stack<Character>();
int len = expr.length();
char exprChar = ' ';
for(int indexOfExpr = 0; indexOfExpr<len; indexOfExpr++){
exprChar = expr.charAt(indexOfExpr);
if(exprChar == '(' || exprChar == '{' || exprChar == '['){
charStack.push(exprChar);
}
else if(exprChar == ')' && !charStack.empty()){
if(charStack.peek() == '('){
charStack.pop();
}
}
else if(exprChar == '}' && !charStack.empty()){
if(charStack.peek() == '{'){
charStack.pop();
}
}
else if(exprChar == ']' && !charStack.empty()){
if(charStack.peek() == '['){
charStack.pop();
}
}
else if(exprChar == ')' || exprChar == '}' || exprChar == ']' ){
return false;
}
}
if(!charStack.empty())
return false;
return true;
}
}