Interpreter design function issues (eclipse) - java

My code is faulty in that it doesn't evaluate each word of the sentence entered by the user.
The interpreter must read from a file the instructions of a program written. In
case of an error in an instruction, the interpreter must stop and show the line number of the instruction that provoked the error.
Am I missing a library for the error message? I've heard Maven has tools that does exactly that, have you?
Click here to see ideal sample output.
Click here to see program description.
public class TokenVerifier {
public static String askInput() {
Scanner input = new Scanner(System.in);
return input.nextLine();
};
public static boolean isString (String str) {
int i = 0, last = str.length() - 1;
if(str.isEmpty())
return false;
if(str.charAt(i) == '"' && (str.charAt(last)) == '"') {
return true;
}
return false;
}
public static boolean logical(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals(".OR.") || str.equals(".AND.")|| str.equals(".NOT.")) {
result = true;
}
return result;
}
public static boolean rem(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals("REM")) {
result = true;
}
return result;
}
public static boolean print(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals("PRINT")) {
result = true;
}
return result;
}
public static boolean read(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals("READ")) {
result = true;
}
return result;
}
public static boolean isIf(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals("IF")) {
result = true;
}
return result;
}
public static boolean isThen(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals("THEN")) {
result = true;
}
return result;
}
public static boolean isEnd(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals("END")) {
result = true;
}
return result;
}
public static boolean relational(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals(".GT.") || str.equals(".LT.")|| str.equals(".EQ.")||str.equals(".GE.")||str.equals(".LE.")||str.equals(".NE.")) {
result = true;
}
return result;
}
public static boolean arithmetic(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals(".ADD.") || str.equals(".SUB.")|| str.equals(".MUL.")||str.equals(".DIV.")) {
result = true;
}
return result;
}
public static boolean sign(String in) {
boolean result = false;
char[] chars = in.toCharArray();
if (in.isEmpty())
return false;
if(chars[0] == '+' ||chars[0] == '-')
result = true;
return result;
}
public static boolean alphabet(String name) {
char[] chars = name.toCharArray();
if (name.isEmpty())
return false;
for (char c : chars) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
public static boolean digit(String name) {
char[] chars = name.toCharArray();
if (name.isEmpty())
return false;
for (char c : chars) {
if(!Character.isDigit(c)) {
return false;
}
}
return true;
}
public static boolean variable(String in) {
int i = 0;
String temp = in.toUpperCase();
if(temp.equals("REM") ||temp.equals("READ")||temp.equals("PRINT")||temp.equals("IF")||temp.equals("THEN")|| temp.equals("END"))
return false;
if(alphabet(in)) {
if( (in.charAt(i) >= 'a' && in.charAt(i) <= 'f') || (in.charAt(i) >= 'A' && in.charAt(i) <= 'F'))
System.out.println(" Integer Type");
if( (in.charAt(i) >= 'g' && in.charAt(i) <= 'n') || (in.charAt(i) >= 'G' && in.charAt(i) <= 'N'))
System.out.println(" Real Number Variable");
if( (in.charAt(i) >= 'o' && in.charAt(i) <= 'z') || (in.charAt(i) >= 'O' && in.charAt(i) <= 'Z'))
System.out.println("String Variable");
return true;
}
return false;
}
public static boolean unsignedInteger(String in) {
if(digit(in))
return true;
return false;
}
public static boolean signedInteger(String name) {
if(sign(name)) {
char[] chars = new char[name.length()-1];
int start = 0;
for(int i = 1;i <= name.length() - 1;i++){
chars[start] = name.charAt(i);
start++;
}
String str = new String(chars);
if(digit(str))
return true;
}
return false;
}
public static boolean decimalPoint(String in) {
char[] chars = in.toCharArray();
int count = 0;
if (in.isEmpty())
return false;
if(chars[0] == '.'|| chars[in.length() - 1] == '.')
return false;
for(int i = 0; i <= in.length() - 1;i++) {
if(chars[i] == '.') {
count++;
}
}
if(count == 1)
return true;
return false;
}
public static boolean realUnsigned(String in) {
String unsignedPart = "", decimalPart = "",intPart = in.toUpperCase(), realPart = "";
int indexOfPoint = 0;
if (in.isEmpty())
return false;
if (sign(intPart) == false){
if(exponent(intPart)) {
realPart = intPart.substring(0, intPart.indexOf('E'));
if(decimalPoint(realPart)) {
unsignedPart = realPart.substring(1, intPart.indexOf('.'));
indexOfPoint = realPart.indexOf('.');
decimalPart = realPart.substring(indexOfPoint + 1);
if(digit(unsignedPart)&&digit(decimalPart))
return true;
}
}
else {
if(decimalPoint(in)) {
unsignedPart = in.substring(1, intPart.indexOf('.'));
indexOfPoint = in.indexOf('.');
decimalPart = in.substring(indexOfPoint + 1);
if(digit(unsignedPart)&&digit(decimalPart))
return true;
}
}
}
return false;
}
public static boolean realSigned(String in)
{
String unsignedPart = "", decimalPart = "",intPart = in.toUpperCase(), realPart = "";
int indexOfPoint = 0;
if (in.isEmpty())
return false;
if (sign(intPart)){
if(exponent(intPart)) {
realPart = intPart.substring(0, intPart.indexOf('E'));
if(decimalPoint(realPart)) {
unsignedPart = realPart.substring(1, intPart.indexOf('.'));
indexOfPoint = realPart.indexOf('.');
decimalPart = realPart.substring(indexOfPoint + 1);
if(digit(unsignedPart)&&digit(decimalPart))
return true;
}
}
else {
if(decimalPoint(in)) {
unsignedPart = in.substring(1, intPart.indexOf('.'));
indexOfPoint = in.indexOf('.');
decimalPart = in.substring(indexOfPoint + 1);
if(digit(unsignedPart)&&digit(decimalPart))
return true;
}
}
}
return false;
}
public static boolean exponent(String in) {
String unsignedPart = "", decimalPart = "",str = in.toUpperCase(), afterExponent ="";
int indexOfPoint = 0, indexOfExponent = 0;
char[] chars = str.toCharArray();
int count = 0;
if (in.isEmpty())
return false;
for(int i = 0; i <= str.length() - 1;i++) {
if(chars[i] == 'E') {
count++;
}
if(count == 1) {
indexOfExponent = str.indexOf('E');
if(str.length()-1 == indexOfExponent)
return false;
afterExponent = str.substring(indexOfExponent + 1);
if(decimalPoint(afterExponent)) {
if(sign(afterExponent)) {
unsignedPart = afterExponent.substring(1, afterExponent.indexOf('.'));
indexOfPoint = afterExponent.indexOf('.');
decimalPart = afterExponent.substring(indexOfPoint + 1);
if(digit(unsignedPart)&&digit(decimalPart))
return true;
}
else {
unsignedPart = afterExponent.substring(0, afterExponent.indexOf('.'));
indexOfPoint = afterExponent.indexOf('.');
decimalPart = afterExponent.substring(indexOfPoint + 1);
if(digit(unsignedPart)&&digit(decimalPart))
return true;
}
}
}
}
return false;
}
public static boolean tokenVerifier(String input) {
if(logical(input))
return true;
if(relational(input))
return true;
if(variable(input))
return true;
if(isString(input))
return true;
if(unsignedInteger(input))
return true;
if(signedInteger(input))
return true;
if(realUnsigned(input))
return true;
if(realSigned(input))
return true;
if(arithmetic(input))
return true;
if(rem(input))
return true;
if(print(input))
return true;
if(read(input))
return true;
if(isEnd(input))
return true;
if(isThen(input))
return true;
if(isIf(input))
return true;
return false;
}
/**********************************************************************************************************************************************************/
/**************************************************************** SENTENCE VERIFIER *****************************************************************/
public static boolean sentenceVerifier(String in) {
String tokens[] = in.split(" ");
int indexOfStringArray = tokens.length;
for(int i = 0; i <= indexOfStringArray - 1; i++) {
if(tokenVerifier(tokens[i]))
System.out.print("Token");
else
System.out.print("Not Token");
}
return false;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String in = input.nextLine();
sentenceVerifier(in);
}
}

Related

Java Balanced String not using stack

I need to check if given String is balanced or not.
This is similar task like that one with balanced parenthesis.
Please let me know if this is understand for you.
try this
public class CheckBalance {
public static void main(String[] args) {
System.out.println(check("asdfgh()hgfdsa"));
}
static boolean isClosing(char first, char sec)
{
if (first == '(' && sec == ')') {
return true;
} else if (first == '{' && sec == '}' ) {
return true;
} else if (first == '[' && sec == ']') {
return true;
}//add other the different Chars
else if(first == sec){
return true;
}
return false;
}
static boolean check(String value) {
if (value != null) {
char[] valueAsArray = value.toCharArray();
int size = valueAsArray.length;
if (size == 0) {
return true;
} else if (size == 1) {
return true;
} else {
for (int i = 0; i < size; i++) {
if (!isClosing(valueAsArray[i], valueAsArray[size - (i+1)])){
return false;
}
if (i == (size-1)/2) {
break;
}
}
return true;
}
} else {
return true;
}
}
}
public boolean isBalanced(String s) {
return isBalanced(s, 0, new LinkedList<>());
}
private boolean isBalanced(String s, int index, LinkedList<Character> stack) {
if (index >= s.length())
return stack.isEmpty();
char c = s.charAt(index);
if (!stack.isEmpty() && Character.compare(c, stack.getLast()) == 0) {
stack.removeLast();
if (isBalanced(s, index + 1, stack))
return true;
stack.add(c);
}
stack.add(c);
return isBalanced(s, index + 1, stack);
}
ABAB is wrong right ? it is the same with parenthesis ?
public boolean isBalanceString(String input)
{
int firstIndex =0;
int lastIndex = input.length()-1;
while (firstIndex<lastIndex)
{
if(input.charAt(firstIndex) != input.charAt(lastIndex))
{
return false;
}
firstIndex++;
lastIndex--;
}
return true;
}

Textfield JavaFX with dynamic mask for monetary values (Using TextFormatter)

i'm using TextFomater to make my TextField as a dynamic monetary textfield, using the following code:
public class MoneyTextFieldOperator implements UnaryOperator<TextFormatter.Change>
{
final char seperatorChar = '.';
final Pattern p;
int length;
public MoneyTextFieldOperator(int length) {
this.length=length;
this.p = Pattern.compile("[0-9. ]*");
}
#Override
public TextFormatter.Change apply(final TextFormatter.Change c) {
if (c.isContentChange() && c.getControlNewText().length() > length) {
return null;
}
else {
if (!c.isContentChange()) {
return c;
}
final String newText = c.getControlNewText();
if (newText.isEmpty()) {
return c;
}
if (!this.p.matcher(newText).matches()) {
return null;
}
final int suffixCount = c.getControlText().length() - c.getRangeEnd();
int digits = suffixCount - suffixCount / 4;
final StringBuilder sb = new StringBuilder();
if (digits % 3 == 0 && digits > 0 && suffixCount % 4 != 0) {
sb.append('.');
}
for (int i = c.getRangeStart() + c.getText().length() - 1; i >= 0; --i) {
final char letter = newText.charAt(i);
if (Character.isDigit(letter)) {
sb.append(letter);
if (++digits % 3 == 0) {
System.out.println("digits : "+digits);
sb.append('.');
}
}
}
if (digits % 3 == 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.reverse();
final int length = sb.length();
c.setRange(0, c.getRangeEnd());
c.setText(sb.toString());
c.setCaretPosition(length);
c.setAnchor(length);
return c;
}}
And calling it as follow :
montantTextField.setTextFormatter(new TextFormatter(new MoneyTextFieldOperator(10)));
the issue is that it's valable just for integer numbers, and i want make it now valable for decimal numbers, so when the user type 254648,32
it converts it to 254.648,32
here is a proposed solution using numberformat :
public class MoneyTextFieldOperator implements UnaryOperator<TextFormatter.Change> {
Pattern p;
int length;
public MoneyTextFieldOperator(int length) {
this.length = length;
this.p = Pattern.compile("[0-9. ,]*");
}
#Override
public TextFormatter.Change apply(TextFormatter.Change c) {
Pattern acceptedKeywords = Pattern.compile("[0-9 . ,]*");
int wholeNumberLength = 9;
int decimalPartLength = 2;
String newText = c.getControlNewText();
String wholeNumber;
String decimalPart;
if (newText.contains(",")) {
wholeNumber = newText.substring(0, newText.indexOf(","));
decimalPart = newText.substring(newText.indexOf(",") + 1, newText.length());
} else {
wholeNumber = newText;
decimalPart = "";
}
Matcher matcher = acceptedKeywords.matcher(newText);
boolean isMatchingWithAcceptedKeywords = matcher.matches();
String letter = c.getText();
if (newText.isEmpty()) {
return c;
} else if (!c.isContentChange()) {
return c;
} else if (countChar(c.getControlNewText(), ',') > 1) {
return null;
} else if (!isMatchingWithAcceptedKeywords) {
return null;
} else if (wholeNumber.replace(".", "").length() > wholeNumberLength || decimalPart.length() > decimalPartLength) {
return null;
} else if (c.getControlNewText().charAt(0)==',') {
return null;
}
else {
c.setRange(0, c.getControlText().length());
if (newText.contains(",")) {
c.setText(NumbersTools.getMonetaryFormat(Integer.parseInt(wholeNumber.replace(".", ""))) + "," + decimalPart);
} else {
c.setText(NumbersTools.getMonetaryFormat(Integer.parseInt(wholeNumber.replace(".", ""))));
}
c.setCaretPosition(c.getText().length());
c.setAnchor(c.getText().length());
return c;
}
}
public int countChar(String string, char charactere) {
int x = 0;
for (int i = 0; i <= string.length() - 1; ++i) {
if (string.charAt(i) == charactere) {
++x;
}
}
return x;
}
and you use it as follow :
textField.setTextFormatter(new TextFormatter<Object>(new MoneyTextFieldOperator(10)));

Implementing Huffman class into another class

I almost have a working Huffman algorithm but I'm having trouble figuring out how to implement it / or make it work together with the Code class. It is my method generateHuffmanCode that needs to be working with the Code class.
I don't know if I'm missing something or if I'm just using the wrong approach.
My Huffman class
package code;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import code.Code;
import application.TCode;
class Node{
Character ch;
Integer freq;
Node left = null, right = null;
Node(Character ch, Integer freq){
this.ch = ch;
this.freq = freq;
}
public Node (Character ch, Integer freq, Node left, Node right) {
this.ch = ch;
this.freq = freq;
this.left = left;
this.right = right;
}
}
public class Huffman {
public static void encode(Node root, String str, Map<Character, String> huffmanCode) {
if (root == null) {
return;
}
if(isLeaf(root)) {
huffmanCode.put(root.ch, str.length() > 0 ? str : "1");
}
encode(root.left, str + '0', huffmanCode);
encode(root.right, str + '1', huffmanCode);
}
public static int decode(Node root, int index, StringBuilder sb) {
if(root == null) {
return index;
}
index++;
if(isLeaf(root)) {
System.out.println(root.ch);
}
index++;
root = (sb.charAt(index) == '0') ? root.left : root.right;
index = decode(root, index, sb);
return index;
}
public static boolean isLeaf(Node root) {
return root.left == null && root.right == null;
}
public static void generateHuffmanCode(Code c) {
// if(c == null || c.length() == 0) {
// return;
// }
Map<Character, double> freq = new HashMap<>(); // why can't I use a double in Map<Character, double>??
for(char s : probability.toCharArry()){
freq.put(s, freq.getOrDefault(s, 0) + 1);
}
PriorityQueue<Node> pq;
pq = new PriorityQueue<>(Comparator.comparingInt(l -> l.freq));
for(var entry: freq.entrySet()) {
pq.add(new Node(entry.getKey(), entry.getValue()));
}
while (pq.size() != 1) {
Node left = pq.poll();
Node right = pq.poll();
int sum = left.freq + right.freq;
pq.add(new Node(null, sum, left, right));
}
Node root = pq.peek();
Map<Character, String> huffmanCode = new HashMap<>();
encode(root, "", huffmanCode);
System.out.println("Huffman Codes are: " + huffmanCode);
System.out.println(probability);
StringBuilder sb = new StringBuilder();
for(char s : probability.toCharArray()) {
sb.append(huffmanCode.get(s));
}
System.out.println("The endcoded String is: " + sb);
System.out.println("The decoded String is: " );
if (isLeaf(root)) {
while (root.freq-- > 0) {
System.out.println(root.ch);
}
} else {
int index = -1;
while(index < sb.length() - 1) {
index = decode(root, index, sb);
}
}
}
public static void main(String[] args) {
generateHuffmanCode(Code probability);
// Code.CodeItem[] ci = {
// new Code.CodeItem("A", 0.12),
// new Code.CodeItem("B", 0.19),
// new Code.CodeItem("C", 0.40),
// new Code.CodeItem("D", 0.13),
// new Code.CodeItem("E", 0.16)
// };
// Code c = new Code(ci);
}
}
And my Code class
package code;
public final class Code {
private CodeItem[] item = null;
public final static class CodeItem {
private String symbol;
private double probability; // the sum of all probabilities must be approx. 1
private String encoding; // a string containing only '0' and '1'
public CodeItem(String symbol, double probability, String encoding) {
this.symbol = symbol.trim();
this.probability = probability;
this.encoding = encoding;
if (!is01() || this.symbol == null || this.symbol.length() == 0 || this.probability < 0.0)
throw new IllegalArgumentException();
}
public CodeItem(String symbol, double probability) {
this(symbol, probability, null);
}
public String getSymbol() {
return symbol;
}
public double getProbability() {
return probability;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public boolean is01() {
if (encoding == null || encoding.length() == 0)
return true;
for (int i = 0; i < encoding.length(); ++i)
if ("01".indexOf(encoding.charAt(i)) < 0)
return false;
return true;
}
}
public Code(CodeItem[] codeItem) {
if (codeItem == null || codeItem.length == 0)
throw new IllegalArgumentException();
double sum = 0.0;
for (int i = 0; i < codeItem.length; ++i) {
sum += codeItem[i].probability;
if (codeItem[i].probability == 0.0)
throw new IllegalArgumentException();
}
if (Math.abs(sum - 1.0) > 1e-10)
throw new IllegalArgumentException();
item = new CodeItem[codeItem.length];
for (int i = 0; i < codeItem.length; ++i)
item[i] = codeItem[i];
}
public boolean is01() {
for (int i = 0; i < item.length; ++i)
if (!item[i].is01())
return false;
return true;
}
public double entropy() {
double result = 0.0;
for(int i = 0; i < item.length; ++i)
result += item[i].probability * (-Math.log(item[i].probability) / Math.log(2.0));
return result;
}
public double averageWordLength() {
double result = 0.0;
for(int i = 0; i < item.length; ++i)
result += item[i].encoding.length() * item[i].probability;
return result;
}
public boolean isPrefixCode() {
for(int i = 1; i < item.length; ++i)
for(int j = 0; j < i; ++j)
if (item[i].encoding.startsWith(item[j].encoding) || item[j].encoding.startsWith(item[i].encoding))
return false;
return true;
}
public int size() {
return item.length;
}
public CodeItem getAt(int index) {
return item[index];
}
public CodeItem getBySymbol(String symbol) {
for (int i = 0; i < item.length; ++i) {
if (item[i].symbol.equals(symbol))
return item[i];
}
return null;
}
public String toString() {
String result = "";
for(int i = 0; i < item.length; ++i) {
result += item[i].symbol + " (" + item[i].probability + ") ---> " + item[i].encoding + "\n";
}
return result.substring(0, result.length()-1);
}
}

Better way to call my methods in the main method for Connect Four

I'm building a program to play Connect Four. I have all my methods done and I'm just building my main method up to actually play the game. Is there a more efficient way to use my Play class than manually inputting the code the way I am? I was fine with doing this until I realized that I don't know how to find a winner doing it this way. Is there a loop I can use that'll properly go through my methods and make the main class tidier and more efficient?
Here is my code:
import java.util.Scanner;
public class Play {
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
System.out.print("Welcome to Connect 4. Please enter your names. \nPlayer 1 Name: ");
String name1 = keyboard.nextLine();
System.out.print("Player 2 Name: ");
String name2 = keyboard.nextLine();
System.out.println(name1 + " - you have red chips \"R\" and you go first.");
Connect4Board game = new Connect4Board(6,7);
System.out.print(game);
System.out.println("Enter a column between 1-7: ");
int column = keyboard.nextInt();
game.add(column, "R");
System.out.print(game);
System.out.print(name2 + " - you have yellow chips \"Y\" and you go next.");
System.out.println("Enter a column between 1-7: ");
column = keyboard.nextInt();
game.add(column, "Y");
System.out.print(game);
}
}
class Chip { //Chip class determines the color of the chip
//Instance Variables
private String colour;
public Chip (String c) { //Constructor
colour = c;
}
public String getColour(){ //Get Method
return colour;
}
public void setColour(String c){ //Set Method
c = colour;
}
public boolean equals(Chip c){ //Checks if two colors are the same
return this.colour == c.getColour();
}
public String toString(){ //Converts to String
return colour;
}
}
class Board { //Creates a board with x rows and x columns.
//Instance Variables
private int rows;
private int cols;
public Board (int r, int c){ //Constructor
rows = r;
cols = c;
}
public int getRows(){ //Get Methods
return rows;
}
public int getCols(){
return cols;
}
public void setRows(int r){ //Set Methods
r = rows;
}
public void setCols(int c){
c = cols;
}
}
class Connect4Board extends Board {
//Instance Variable
private Chip [][] board;
private String colourOfWin = "";
public Connect4Board(int r, int c){
super(r, c);
board = new Chip[r][c];
}
public Chip[][] getBoard(){
return board;
}
public void setBoard(int r,int c){
setRows(r);
setCols(c);
}
public boolean add(int cols, String colour){
boolean result = true;
int counter = 0;
boolean testPlacement = false;
if(cols>=0 && cols<=6){
}
else
result = false;
if (board[5][cols] != null)
result = false;
for(int row = 5; row >= 0 && testPlacement == false; row--){
if(board[row][cols]==null){
counter += 1;
}
else
testPlacement = true;
}
if(result == true){
board[6-counter][cols] = new Chip(colour);
//
}
return result;
}
public String winType(){
String result;
if(rowWinner()){
result = "Row Winner";
}
else if(columnWinner()){
result = "Column Winner";
}
else if(rightDiagonalWinner() || leftDiagonalWinner()){
result = "Diagonal Winner";
}
else{
result = "No winner yet.";
}
return result;
}
public boolean rowWinner(){
boolean result = false;
boolean result1 = true; //Test the equals to see if true
for(int row=0; row<6 && result == false; row++){ //Nested for loops to proccess array. Row
for(int cols=0; cols<4 && result == false; cols++){ //Column
for(int win=0; win<4; win++){ //Check win
if(board[row][cols] != null && board[row][cols+win] != null){
if(board[row][cols+win].equals(board[row][cols])&& result1 == true ){ //result1 tests to see if the equals is true
}
else
result1 = false;
}
else
result1 = false;
}
if(result == true)
colourOfWin = board[row][cols].getColour();
result = result1;
}
}
return result;
}
public boolean columnWinner(){
boolean result = false;
boolean result1 = true; //Test the equals to see if true
for(int row=0; row<3 && result == false; row++){ //Nested for loops to proccess array. Row
for(int cols=0; cols<7 && result == false; cols++){ //Column
for(int win=0; win<4; win++){ //Check win
if(board[row][cols] != null && board[row+win][cols] != null){
if(board[row+win][cols].equals(board[row][cols])&& result1 == true ){ //result1 tests to see if the equals is true
}
else
result1 = false;
}
else
result1 = false;
}
if(result == true)
colourOfWin = board[row][cols].getColour();
result = result1;
}
}
return result;
}
public boolean rightDiagonalWinner(){
boolean result = false;
boolean result1 = true; //Test the equals to see if true
for(int row=0; row<3 && result == false; row++){ //Nested for loops to proccess array. Row
for(int cols=0; cols<4 && result == false; cols++){ //Column
for(int win=0; win<4; win++){ //Check win
if(board[row][cols] != null && board[row+win][cols+win] != null){
if(board[row+win][cols+win].equals(board[row][cols])&& result1 == true ){ //result1 tests to see if the equals is true
}
else
result1 = false;
}
else
result1 = false;
}
if(result == true)
colourOfWin = board[row][cols].getColour();
result = result1;
}
}
return result;
}
public boolean leftDiagonalWinner(){
boolean result = false;
boolean result1 = true; //Test the equals to see if true
for(int row=0; row<3 && result == false; row++){ //Nested for loops to proccess array. Row
for(int cols=6; cols<2 && result == false; cols--){ //Column
for(int win=0; win<4; win++){ //Check win
if(board[row][cols] != null && board[row+win][cols-win] != null){
if(board[row+win][cols-win].equals(board[row][cols])&& result1 == true ){ //result1 tests to see if the equals is true
}
else
result1 = false;
}
else
result1 = false;
}
if(result == true)
colourOfWin = board[row][cols].getColour();
result = result1;
}
}
return result;
}
public boolean winner(){
return rowWinner() || columnWinner() || rightDiagonalWinner() || leftDiagonalWinner();
}
public String toString(){
String b;
b="\tCol.\n";
for (int j=0;j<7;j++){
b=b+"\t"+(j+1);
}
b=b+"\n";
for (int i=0;i<6;i++){
b=b+(i+1)+"\t";
for(int j=0;j<7;j++){
if(board[5-i][j]==null){
b=b+" \t";
}
else{
b=b+board[5-i][j].getColour()+"\t";
}
}
b=b+"\n\n";
}
return b;
}
}

My parser function is not working

I was designing a simple parser(it works on a simple version of Shunting Yard Algorithm). Here's my code(I haven't dealt with associativity).
public class Parser {
String stack[] = new String[50];
String res = "";
int top = 0;
Operator o1 = new Operator("", 0, 0);
public String parse(String x) {
push("(");
x = x + ")";
for (int i = 0; i < x.length(); i++) {
if (o1.isNumber(x.charAt(i) + "")) {
res = res + x.charAt(i);
} else if (x.charAt(i) == '(') {
push("(");
} else if (o1.isOperator("" + x.charAt(i))) {
if (top != -1) {
while ((top != -1) && (o1.isOperator(stack[top]))) {
int m = o1.getOperatorIndex(stack[top]);
int mp = o1.op[m].prec;
int xp = o1.op[o1.getOperatorIndex("" + x.charAt(i))].prec;
if (m >= xp) {
res = res + stack[top];
}
top--;
}
}
push("" + x.charAt(i));
} else {
if (top != -1) {
while ((top != -1) && (stack[top] != ")")) {
if (o1.isOperator(stack[top])) {
res = res + stack[top];
}
top--;
}
}
}
}
return res;
}
public void push(String m) {
if (top != 49) {
stack[top] = m;
top++;
} else {
System.out.println("Overflow");
}
}
}
I guess you won't need the Operator class's code. When I try executing parse("1+2"), it just returns 12 and not the + sign. What is wrong? and yes, o[0] is +,o[1] is -,o[2] is*, o[3] is /

Categories