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).
Related
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)
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");
}
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.
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 == ']';
}
another question to put out there. I was working on an assignment to create hash functions and all that jazz, and i have stumbled across a small problem.
Line 35:21, where it reads arrpos += prearrpo & ______,
in my head works... What im trying to do is access arr.length from the HashTable() method. I've read around, suggestions with needing to creat an object of size arr.length; however in my mind, this seems overly complicated-
Is there another way i can access the variable in the HashTable method, but inside the insert method?
Another not so important question involves the giant block of if() statements in the letter(char c) class; im certain there must be a shorter way of doing this... I would have initially used the ascii values; but the specifications were quite particular about using the values 1-26 for lower/upper case letters-
Thanks
import java.io.*;
public class HashTable {
public HashTable() {
//Create an array of size 101
String arr[] = new String[101];
//System.out.println("Size1: ");
}
public HashTable(int tsize) {
int size = 2 * tsize;
//System.out.println("Size: " + size);
boolean isPrime = checkPrime(size);
//System.out.println("IsPrime: " + isPrime);
while (isPrime == false) {
//System.out.println("Size: " + size);
size++;
isPrime = checkPrime(size);
}
//System.out.println("Size: " + size);
String arr[] = new String[size];
}
public boolean insert(String line) {
String str = line;
char[] ch = str.toCharArray();
int slen = str.length();
int arrpos = 0;
int hash = slen;
for (int i = 0; i < slen; i++) {
double prearrpo = letter(ch[i]) * Math.pow(32, (hash - 1));
arrpos += prearrpo % arr.length();
hash--;
}
System.out.println(arrpos);
System.out.println("array size:");
System.out.println();
return false;
}
private int letter(char c) {
char ch = c;
if (ch == 'A' || ch == 'a') {
return 1;
}
if (ch == 'B' || ch == 'b') {
return 2;
}
if (ch == 'C' || ch == 'c') {
return 3;
}
if (ch == 'D' || ch == 'd') {
return 4;
}
if (ch == 'E' || ch == 'e') {
return 5;
}
if (ch == 'F' || ch == 'f') {
return 6;
}
if (ch == 'G' || ch == 'g') {
return 7;
}
if (ch == 'H' || ch == 'h') {
return 8;
}
if (ch == 'I' || ch == 'i') {
return 9;
}
if (ch == 'J' || ch == 'j') {
return 10;
}
if (ch == 'K' || ch == 'k') {
return 11;
}
if (ch == 'L' || ch == 'l') {
return 12;
}
if (ch == 'M' || ch == 'm') {
return 13;
}
if (ch == 'N' || ch == 'n') {
return 14;
}
if (ch == 'O' || ch == 'o') {
return 15;
}
if (ch == 'P' || ch == 'p') {
return 16;
}
if (ch == 'Q' || ch == 'q') {
return 17;
}
if (ch == 'R' || ch == 'r') {
return 18;
}
if (ch == 'S' || ch == 's') {
return 19;
}
if (ch == 'T' || ch == 't') {
return 20;
}
if (ch == 'U' || ch == 'u') {
return 21;
}
if (ch == 'V' || ch == 'v') {
return 22;
}
if (ch == 'W' || ch == 'w') {
return 23;
}
if (ch == 'X' || ch == 'x') {
return 24;
}
if (ch == 'Y' || ch == 'y') {
return 25;
}
if (ch == 'Z' || ch == 'z') {
return 26;
}
return 0;
}
public boolean lookUp(String string) {
//
return false;
}
public String getNum() {
//
return null;
}
public int length() {
return 0;
}
private static boolean checkPrime(int size) {
if (size % 2 == 0) {
return false;
}
double c = Math.sqrt(size);
for (int i = 3; i < c; i += 2) {
if (size % i == 0) {
return false;
}
}
return true;
}
}
public HashTable() is a constructor. Your arr[] should actually be a private member of your class and you should initialize it in all constructors or make sure you never access without intializing it.
public class HashTable {
private String[] arr;
public HashTable()
{
//Create an array of size 101
arr[] = new String[101];
System.out.println("Size1: ");
}
etc...
Since it seems that your implementation is array backed, you need to declare the array as a member variable:
public class HashTable {
String arr[] = null;
And then initialize it in your constructors ( note in Java world methods like HashTable() is called a constructor) as :
arr = new String[whatever_size];