Need help with scanner class for creating tokens - java

Errors im getting: cannot find symbol
constructor method Token. but i do
have a constructor in Token class
cannot find symbol variable
tokenCode. i clearly use it alll over
and i think i initialized it properly
so whats wrong?
cannot find symbol variable scantest.
i have that in same folder where all
classes are in why wont it read it?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
public class scanner implements CompilerConstants {
private char c;
private BufferedReader source;
public int token;
private String attr = "";
//private int val = '0';
private
public scanner(BufferedReader buffer) {
source = buffer;
getChar();
} //constructor of scanner
public void getChar()
{
c = (char)(source.read());
//do a read in
}
//lookup for finding identifiers
public boolean lookup(String word)
{
boolean check = false;
for(int i=0; i < RESERVEDWORD.length;i++)
if(word==(RESERVEDWORD[i]))
{
check = true;
}
return check;
}
//public boolean T(int tcc, String attt) //to return token
//{
// tokenCode = tcc;
// attribute = attt;
// return T;
// }
public Token nextToken() throws IOException
{
attr = "";
//need to save to do lookup see if its identifier or not
while(c!=EOFCHAR); //if not end of file then do
{
while (Character.isWhitespace(c))//remove white space, check whether is letter or digit
{
getChar();
}
if (Character.isLetter(c))
{
while(Character.isLetterOrDigit(c))
{
attr = attr + c;
getChar();
}
return new Token(lookup(attr), attr); //
}
else if (Character.isDigit(c)) {
while(Character.isDigit(c))
{
attr = attr + c;
getChar();
}
return new Token(NUMBER, attr);
}
else {
switch (c) {
case '<' : getChar();
if(c=='>')
{
getChar();
return new Token(NE, null);
}
else if (c=='=')
{
getChar();
return new Token(LE, null);
}
return new Token(LT, null);
case '>' : getChar();
if(c=='<')
{
getChar();
return new Token(NE, null);
}
else if (c=='=')
{
getChar();
return new Token(GE, null);
}
return new Token(GT, null);
case '=' : getChar();
return new Token(EQ, null);
case '|' : getChar();
return new Token(OR, null);
case '+' : getChar();
return new Token(PLUS, null);
case '-' : getChar();
return new Token(MINUS, null);
case '*' : getChar();
return new Token(TIMES, null);
case '/' : getChar();
return new Token(DIVIDE, null);
case '[' : getChar();
return new Token(LEFTSQ, null);
case ']' : getChar();
return new Token(RIGHTSQ, null);
case '(' : getChar();
return new Token(LEFTPAREN, null);
case ')' : getChar();
return new Token(RIGHTPAREN, null);
case ',' : getChar();
return new Token(COMMA, null);
case EOFCHAR : getChar();
return new Token(EOF, null);
}
} // switch
//return EOF.Token;
return Token(tokenCode, attr); //tokenAttribute
} // if
// return Token;
} // getToken
public static void main(String[] args)
{
BufferedReader source = new BufferedReader(new FileReader(scantest.echo));
}
}
Token class
public class Token implements CompilerConstants {
private int tokenCode;
private String attribute;
public Token(int tc, String att) //constructor
{
tokenCode = tc;
attribute = att;
}
public int getToken()//return tokencode
{
return tokenCode;
}
//return token attribute
public String tokenAttribute()
{
return attribute;
}
public String toString(){
String tokenString = tokenCode + " ";
switch (tokenCode) { //// relational expressions for metasymbols
case AND: return (tokenString + "/n AND");
case IDENTIFIER: return (tokenString + "/n IDENTIFIER" + attribute);
case OR: return (tokenString + "/n OR");
case NOT: return (tokenString + "/n NOT");
case ARRAY: return (tokenString + "/n ARRAY");
case BEGIN: return (tokenString + "/n BEGIN ");
case BOOLEAN: return (tokenString + "/n BOOLEAN ");
case DO: return (tokenString + "/n DO ");
case ELSE: return (tokenString + "/n ELSE");
case END: return (tokenString + "/n END");
case FOR: return (tokenString + "/n FOR");
case FROM: return (tokenString + "/n FROM");
case IF: return (tokenString + "/n IF");
case INTEGER: return (tokenString + "/n INTEGER");
case PROCEDURE: return (tokenString + "/n PROCEDURE");
case PROGRAM: return (tokenString + "/n PROGAM");
case READ: return (tokenString + "/n READ");
case START: return (tokenString + "/n START");
case THEN: return (tokenString + "/n THEN");
case TO: return (tokenString + "/n TO");
case TRUE: return (tokenString + "/n TRUE");
case WHILE: return (tokenString + "/n WHILE");
case WRITE: return (tokenString + "/n WRITE");
case WRITELN: return (tokenString + "/n WRITELN");
case NUMBER: return (tokenString + "/n NUMBER" + attribute);
case STRING: return (tokenString + "/n STRING" + attribute);
case LT: return (tokenString + "/n LT");
case LE: return (tokenString + "/n LE");
case GT: return (tokenString + "/n GT");
case GE: return (tokenString + "/n GE");
case EQ: return (tokenString + "/n EQ");
case NE: return (tokenString + "/n NE");
case PLUS: return (tokenString + "/n PLUS");
case MINUS: return (tokenString + "/n MINUS");
case TIMES: return (tokenString + "/n TIMES");
case DIVIDE: return (tokenString + "/n DIVIDE");
case LEFTSQ: return (tokenString + "/n LEFTSQ");
case RIGHTSQ: return (tokenString + "/n RIGHTSQ");
case LEFTPAREN: return (tokenString + "/n LEFTPAREN");
case COLONEQUAL: return (tokenString + "/n COLONEQUAL");
case COMMA: return (tokenString + "/n COMMA");
case EOF: return (tokenString + "/n EOF");
}
return tokenString;
}
}
CompilerConstants
public interface CompilerConstants {
public static final int AND = 1;
public static final int ARRAY = 2;
public static final int BEGIN = 3;
public static final int BOOLEAN = 4;
public static final int DO = 5;
public static final int ELSE = 6;
public static final int END = 7;
public static final int FALSE = 8;
public static final int FOR = 9;
public static final int FROM = 10;
public static final int IF = 11;
public static final int INTEGER = 12;
public static final int NOT = 13;
public static final int OR = 14;
public static final int PROCEDURE = 15;
public static final int PROGRAM = 16;
public static final int READ = 17;
public static final int START = 18;
public static final int THEN = 19;
public static final int TO = 20;
public static final int TRUE = 21;
public static final int WHILE = 22;
public static final int WRITE = 23;
public static final int WRITELN = 24;
public static final int IDENTIFIER = 30;
public static final int NUMBER = 31;
public static final int STRING = 32;
public static final int LT = 33;
public static final int LE = 34;
public static final int GT = 35;
public static final int GE = 36;
public static final int EQ = 37;
public static final int NE = 38;
public static final int PLUS = 39;
public static final int MINUS = 40;
public static final int TIMES = 41;
public static final int DIVIDE = 42;
public static final int LEFTSQ = 43;
public static final int RIGHTSQ = 44;
public static final int LEFTPAREN = 45;
public static final int RIGHTPAREN = 46;
public static final int COLONEQUAL = 47;
public static final int COMMA = 48;
public static final int EOF = 99;
public static final char EOFCHAR = (char)(-1);
public static final String[] RESERVEDWORD = {"","and","array","begin","boolean",
"do","else","end","false","for","from","if","integer","not","or",
"procedure","program","read","start","then","to","true","while",
"write","writeln"};
public static final boolean DEBUG = true;
} // interface CompilerConstants

This line has a problem:
return new Token(lookup(attr), attr);
The method lookup(attr) returns a boolean but the Token constructor is expecting an int as first argument. I can see:
public Token(int, String)
But not:
public Token(boolean, String)
Maybe you are passing the wrong argument to the existing Token constructor.
Now, regarding this line:
return Token(tokenCode, attr); //tokenAttribute
The tokenCode isn't indeed defined. Where did you initialize it? Where do you use it?
Finally, about:
new FileReader(scantest.echo));
it's hard to answer as you didn't provide the class sources. What is echo exactly? A static attribute?
PS: Your classes should start with a capitalized letter and/or use camel case notation like Scanner or ScanTest instead of scanner and scantest. This is a recommended convention.

Related

Program not comparing JFrame textfield value with number generated in other class

I made a little random math generator, which gives out 2 random numbers and a random operator but when I call my check result method in my ok button, I always get the "Errado" ("Wrong") string which means it's not properly comparing the value of the textfield with the result of whatever math problem was presented. Leaving relevent code from both classes down here with comments on where I'm having issues and 2 for ease of understanding. Help's appreciated!
public class geraAritmetica {
ArrayList<Integer> nums = new ArrayList();
int a;
char ops = '?';
int max = 10;
int min = 1;
int range = max - min + 1;
int res;
Random r = new Random();
public int gerarNums(){
for(int i = 0; i<10; i++){
a = (int) (Math.random()*range) + min;
nums.add(a);
}
return a;
}
public char gerarOps(){
switch(r.nextInt(4)){
case 1 : ops = '+';
res = nums.get(0) + nums.get(1);
break;
case 2: ops = '-';
res = nums.get(0) - nums.get(1);
break;
case 3: ops = '*';
res = nums.get(0) * nums.get(1);
break;
case 4: ops = '/';
res = nums.get(0) / nums.get(1);
break;
default: ops = '+';
res = nums.get(0) + nums.get(1);
break;
}
return ops;
}
public boolean checkRes(){ //everytime I call this method always get the same string "Errado" ("Wrong") in the label.
if(Integer.parseInt(FrameEnsinoAritmetica.jTextField1.getText()) == res){
FrameEnsinoAritmetica.jLabel2.setText("Correto!");
return true;
}
else FrameEnsinoAritmetica.jLabel2.setText("Errado!");
return false;
}
}
public class FrameEnsinoAritmetica extends javax.swing.JFrame {
geraAritmetica a = new geraAritmetica(); //creating object of class at the start of my JFrame class
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { //generating numbers and operator (it prints fine in another label)
int b = a.gerarNums();
int c = a.gerarNums();
char s = a.gerarOps();
jLabel1.setText(b + " " +s+ " " + c);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
a.checkRes(); //everytime I call this method always get the same string "Errado" ("Wrong") in the label.
}
You seem to be referencing to the FrameEnsinoAritmetica class directly not the actual instance of your FrameEnsinoAritmetica jFrame that you see on screen. For example, using this in another class will not reference to the frame that you see on screen:
String text = FrameEnsinoAritmetica.jTextField1.getText();
But using this would work:
String text = yourInstanceOfEnsinoAritmetica.jTextField1.getText();
To fix this we could pass the current instance of the FrameEnsinoAritmetica that is shown on screen into the checkRes method, which we do by modifying checkRes like so, and inside the method we replace FrameEnsinoAritmetica with frame to refer to the current instance:
public boolean checkRes(FrameEnsinoAritmetica frame){ //everytime I call this method always get the same string "Errado" ("Wrong") in the label.
if(Integer.parseInt(frame.jTextField1.getText()) == res){
frame.jLabel2.setText("Correto!");
return true;
}
else frame.jLabel2.setText("Errado!");
return false;
}
Then we just update the jButton1ActionPerformed method to pass this which is the current instance of FrameEnsinoAritmetica into the updated checkRes method:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
a.checkRes(this); //everytime I call this method always get the same string "Errado" ("Wrong") in the label.
}
Fix part 2 (for res not being calculated properly)
public class FrameEnsinoAritmetica extends javax.swing.JFrame {
geraAritmetica a = new geraAritmetica();
public static int b;
public static int c;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
b = a.gerarNums();
c = a.gerarNums();
char s = a.gerarOps(this);
jLabel1.setText(b + " " +s+ " " + c + " ");
}
public class geraAritmetica {
ArrayList<Integer> nums = new ArrayList();
int a;
char ops = '?';
int max = 10;
int min = 1;
int range = max - min + 1;
public static int res;
Random r = new Random();
public int gerarNums(){
for(int i = 0; i<10; i++){
a = (int) (Math.random()*range) + min;
nums.add(a);
}
return a;
}
public char gerarOps(FrameEnsinoAritmetica frame){
switch(r.nextInt(4)){
case 1 : ops = '+';
res = frame.b + frame.c; //checking both variables directly from JFrame class instead of getting through index from ArrayList.
break;
case 2: ops = '-';
res = res = frame.b - frame.c;
break;
case 3: ops = '*';
res = frame.b * frame.c;
break;
case 4: ops = '/';
res = frame.b / frame.c;
break;
default: ops = '+';
res = frame.b + frame.c;
break;
}
return ops;
}
public boolean checkRes(FrameEnsinoAritmetica frame){
if(Integer.parseInt(frame.jTextField1.getText()) == res){
frame.jLabel2.setText("Correto!");
return true;
}
else frame.jLabel2.setText("Errado!");
return false;
}
}

JAVA: error: unexpected type

public abstract class Character{
public enum Type{ ROGUE, PALADIN, JACKIE_CHEN, SKELETON, GOBLIN, WIZARD}
private String name;
private int hitPoints;
private int strength;
private Weapon weapon;
//other attributes
//methods
public Character(Type characterType){
switch(characterType){
case ROGUE:
//set the attributes for a Rogue
name = "Rogue";
// TODO: set other attributes
hitPoints = 55;
strength = 8;
Weapon rogue = new Weapon("Short Sword", 1, 4);
break;
case PALADIN:
//set the attributes for a Rogue
name = "Paladin";
// TODO: set other attributes
hitPoints = 35;
strength = 14;
Weapon paladin = new Weapon("Long Sword",3,7);
break;
case JACKIE_CHEN:
name = "Jackie Chen";
hitPoints =45;
strength = 10;
Weapon jackie = new Weapon("Jump Kick",2, 6);
break;
case SKELETON:
name = "Skeleton";
hitPoints = 25;
strength = 3;
Weapon skeleton = new Weapon("Short Sword" ,1, 4);
break;
case GOBLIN:
name = "Goblin";
hitPoints = 25;
strength = 4;
Weapon goblin = new Weapon("Axe",2,6);
break;
case WIZARD:
name = "Wizard";
hitPoints = 40;
strength = 8;
Weapon wizard = new Weapon("Fire Blast", 4, 10);
break;
}
}
public String getName(){
return name;
}
public int getHitPoints(){
return hitPoints;
}
public int getStrength(){
return strength;
}
public void setStrength(int _strength){
this.strength =_strength;
}
public void setWeapon(Weapon _weapon){
this.weapon = _weapon;
}
public void attack(){
}
public void increaseHitPoints(){
}
public void decreaseHitPoints(){
}
/*public boolean isDefeated(){
}*/
}
import java.util.Scanner;
import java.util.Random;
public class Player extends Character{
// attributes for the plauer class
// initilizes the fields
private int coins;
private Potion[] inventory;
Random randomNums = new Random();
Scanner keyboard = new Scanner(System.in);
//methods
public Player(Type playerType){
super(playerType);
coins = 0;
inventory = new Potion[5];
}
public void increaseStrength(int strengthIncrease){
enemy.getHitPoints() -= playerATK;
}
public int getCoins(){
return coins;
}
public void increaseCoins(int coins){
}
public void decreaseCoins(int coins){
}
public void addToInventory(String a, Type potion){
}
public void removeFromInventory(int index){
}
public void displayInventory(){
}
/*public int getNumOpenSlots(){
return numOpenSlots;
}*/
public void battleMinion(Enemy enemy){
Enemy goblin = new Enemy(Character.Type.GOBLIN);
int playerDamage =0, playerATK =0, enemyATK =0, enemyDamage =0;
if (enemy.getName() == "Goblin" && getName()=="Rogue"){
for (int i = 1; i <= goblin.getNumGoblins(); i++)
{
System.out.printf("***%s vs %s %d***\n", getName(), enemy.getName(), i);
while(enemy.getHitPoints() > 0 && getHitPoints() > 0)
{
playerDamage = randomNums.nextInt(Weapon.SHORT_SWORD_MAX - Weapon.SHORT_SWORD_MIN + 1) + Weapon.SHORT_SWORD_MIN;
playerATK = getStrength() + playerDamage;
enemy.getHitPoints() -= playerATK;
System.out.printf("%s attacks with ATK = %d + %d = %d\n", getName(), getStrength(), playerDamage, playerATK);
System.out.printf("%s HP is now %d - %d = %d\n\n", enemy.getName(), enemy.getHitPoints() + playerATK, playerATK, enemy.getHitPoints());
if (enemy.getHitPoints() <= 0)
break;
enemyDamage = randomNums.nextInt(Weapon.AXE_MAX - Weapon.AXE_MIN + 1) + Weapon.AXE_MAX;
enemyATK = enemy.getStrength() + enemyDamage;
getHitPoints() -= enemyATK;
System.out.printf("%s attacks with ATK = %d + %d = %d\n", getName(), enemy.getStrength(), enemyDamage, enemyATK);
System.out.printf("%s HP is now %d - %d = %d\n\n", getName(), getHitPoints() + enemyATK, enemyATK, getHitPoints());
} // end of while loop
if (getHitPoints() > 0){
System.out.printf("%s defeated %s %d!\n\n", getName(), enemy.getName(), i);
coins = randomNums.nextInt((50 - 30) + 1) + 30;
System.out.println(getName() + " gains " + coins + " gold coins!\n");
//player[4] += coins;
}
else
{
System.out.printf("--%s is defeated in battle!--\n\nGAME OVER\n", getName());
System.exit(0);
}
if(i <= goblin.getNumGoblins() - 1){
System.out.println("Press enter to continue...");
keyboard.nextLine();
}
}
}
Error is as follows
./Player.java:59: error: unexpected type
enemy.getHitPoints() -= playerATK;
^
required: variable
found: value
./Player.java:68: error: unexpected type
getHitPoints() -= enemyATK;
I know this is wrong, but what is the reason behind this? Also I have
public void increaseHitPoints(){
}
public void decreaseHitPoints(){
}
these two class in my character class, I don't how to code to make this work.
getHitPoints() is a method that returns a value. You can't assign anything to that expression, and the -= operator performs both subtraction and assignment.
Instead of
getHitPoints() -= playerATK;
write
setHitPoints (getHitPoints() - playerATK);
or
decreaseHitPointsBy (playerATK); // this approach would require a corresponding
// increaseHitPointsBy (value) method

What is Java Error: 93: Reached end of file while parsing?

This may be a relatively simple question, but why is my program getting this error:Expression.java:93: error: reached end of file while parsing
}
I have tried following multiple guides online, like opening and closing my classes correctly, but unfortunately I still seem to be getting this error.
Here is my code in case this helps:
public class Expression {
private static final String SPACE = " ";
private static final String PLUS = "+";
private static final String MINUS = "-";
public static int rank(String operator) {
switch (operator) {
case "^": //5
return 3;
case "*":
case "/":
return 2;
case PLUS:
case MINUS: //2
return 1;
default:
return -1;
}
}
public static boolean isOperator(String token) { //4
if (rank(token) > 0){
return true;
}
return false;
}
public static int applyOperator(String operator,int op1,int op2){ //7
switch (operator) {
case PLUS:
return op1+op2;
case MINUS:
return op1-op2;
case "*":
return op1*op2;
case "/":
return op1/op2;
default:
return -1;
}
}
public static String toPostfix(String infixExpr) {
StringBuilder output = new StringBuilder();
Stack<String> operators = new ArrayStack<>();
for (String token: infixExpr.split("\\s+")) {
if (isOperator(token)) { // operator //4
// pop equal or higher precedence
while (!operators.isEmpty() &&
rank(operators.peek()) >= rank(token)) {
output.append(operators.pop() + SPACE);
}
operators.push(token);
} else { // operand
output.append(token + SPACE);
}
}
while (!operators.isEmpty()) {
output.append(operators.pop() + SPACE);
}
return output.toString();
}
public class PostFixTest {
public static int evalPostfix(String infixExpr) {
Stack <String> s = new ArrayStack<String>();
String operand = null;
for(int i = 0; i < infixExpr.length(); i++) {
if (Character.isDigit(infixExpr.charAt(i)))
s.push(infixExpr.charAt(i) + "");
else {
if (s.size() > 1) {
int value1 = Integer.parseInt(s.pop());
int value2 = Integer.parseInt(s.pop());
s.push(applyOperator(infixExpr.charAt(i) + "", value1, value2) + "");
}
}
}
return s.pop();
}
}
public static void main(String[] args) {
System.out.println(rank("/"));
String infix = "a * b * c + d ^ e / f";
System.out.println(toPostfix(infix));
System.out.print("Using applyOperator method, 7 * 3 = ");
System.out.println(applyOperator("*", 3, 7));
System.out.print("Using applyOperator method, 50 + 12 = ");
System.out.println(applyOperator("+", 50, 12));
}
You are losing right } in your code last. like:
...
public static void main(String[] args) {
System.out.println(rank("/"));
String infix = "a * b * c + d ^ e / f";
System.out.println(toPostfix(infix));
System.out.print("Using applyOperator method, 7 * 3 = ");
System.out.println(applyOperator("*", 3, 7));
System.out.print("Using applyOperator method, 50 + 12 = ");
System.out.println(applyOperator("+", 50, 12));
}
} // you lost this bracket.

How can I scan a string for only four specific characters?

I want the user to input a DNA sequence, if it doesn't have the letters A, C, T, or G then it should print out an error. But how can I scan the string entered for those specific characters in the constructot method DNASequence?
heres what I have so far.
import java.util.*;
public class DNASequence {
private String DNASequence;//create a private static variable that can be accessed
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please input a sequence of DNA: ");
String DNAInput = input.nextLine();
}
public DNASequence(String DNAStrand){//Constructor Method that takes parameter a string and checks to see if its only A, T, C, G.
DNASequence = DNAStrand;
// Invoke the countLetters method to count each letter
int[] counts = countLetters(DNAStrand.toUpperCase());
// Display results
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0)
System.out.println((char)('a' + i) + " appears " +
counts[i] + ((counts[i] == 1) ? " time" : " times"));
}
}
/** Count each letter in the string */
public static int[] countLetters(String s) {
int[] counts = new int[26];
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i)))
counts[s.charAt(i) - 'a']++;
}
return counts;
}
public String toString(){//Method that just returns the stored sequence
return DNASequence;
}
private static char NucleotideBaseCount(char BaseCount){//Method to count bases
}
private static boolean isSubsequenceOf(String DNAStrand){
}
}
You could use the following regular expression for this: ^[ACTG]+$.
To match the input string against the regex, use String.matches().
Here in a sample implementation based on #NPE 's comment:
import java.util.*;
public class DNASequence
{
private String DNASequence = null; //create a private static variable that can be accessed
public static void main(String[] args)
{
System.out.println("Please input a sequence of DNA: ");
DNASequence dnaS = new DNASequence((new Scanner(System.in)).nextLine().toUpperCase());
}
//Constructor Method that takes parameter a string and checks to see if its only A, T, C, G.
public DNASequence(String DNAStrand) throws IllegalArgumentException
{
if (DNAStrand.matches("^[ATCG]+$"))
{
DNASequence = DNAStrand;
}
else
{
throw new IllegalArgumentException("DNA Sequences should only contain A, T, C, G charaters");
}
}
/** Count each letter in the string */
public int[] countLetters() throws IllegalArgumentException
{
int[] counts = new int[4];
if (DNASequence != null)
{
for (int i = 0; i < DNASequence.length(); i++)
{
switch (DNASequence.charAt(i))
{
case 'A':
counts[0]++;
break;
case 'T':
counts[1]++;
break;
case 'C':
counts[2]++;
break;
case 'G':
counts[3]++;
break;
default:
throw new IllegalArgumentException("DNA Sequences should only contain A, T, C, G charaters, found: " + DNASequence.charAt(i));
}
}
}
return counts;
}
//Method that just returns the stored sequence
public String toString()
{
return DNASequence;
}
private char NucleotideBaseCount(char BaseCount){//Method to count bases
return 'a'; // replace with real implementation
}
private boolean isSubsequenceOf(String DNAStrand)
{
return false; // repalce with real implementation
}
}

Postfix evaluation in java with stack

I made this program that evaluates a postfix expression.
It works fine if only single digit numbers are used.
My problem is how do I push multiple-digit numbers if input has spaces?
ex. input: 23+34*- output is -7
but if I input: 23 5 + output is only 3(which is the digit before the space)
it should have an output of 28
my codes:
public class Node2
{
public long num;
Node2 next;
Node2(long el, Node2 nx){
num = el;
next = nx;
}
}
class stackOps2
{
Node2 top;
stackOps2(){
top = null;
}
public void push(double el){
top = new Node2(el,top);
}
public double pop(){
double temp = top.num;
top = top.next;
return temp;
}
public boolean isEmpty(){
return top == null;
}
}
public class ITP {
static stackOps2 so = new stackOps2();
public static final String operator = "+-*/^";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the infix:");
String s = input.next();
String output;
InToPost theTrans = new InToPost(s);
output = theTrans.doTrans();
System.out.println("Postfix is " + output + '\n');
System.out.println(output+" is evaluated as: "+evaluate(output));
}
public static double evaluate(String value)throws NumberFormatException{
for(int i=0;i<value.length();i++){
char val = value.charAt(i);
if(Character.isDigit(value.charAt(i))){
String v = ""+val;
so.push(Integer.parseInt(v));
}
else if(isOperator(val)){
double rand1=so.pop();
double rand2=so.pop();
double answer ;
switch(val){
case '+': answer = rand2 + rand1;break;
case '-': answer = rand2 - rand1;break;
case '*': answer = rand2 * rand1;break;
case '^': answer = Math.pow(rand2, rand1);break;
default : answer = rand2 / rand1;break;
}
so.push(answer);
}
else if(so.isEmpty()){
throw new NumberFormatException("Stack is empty");
}
}
return so.pop();
}
public static boolean isOperator(char ch){
String s = ""+ch;
return operator.contains(s);
}
}
This is a small, self-contained example that does all the string parsing and evaluation. The only difference from your example is that it accepts the whole string at once instead of using a Scanner. Note the use of Integer.parseInt -- that's missing in your example. I think you can easily extend this for your needs.
#SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args) {
final String in = "5 9 + 2 * 6 5 * +";
final Deque<Object> s = new LinkedList();
for (String t : in.split(" ")) {
if (t.equals("+")) s.push((Integer)s.pop() + (Integer)s.pop());
else if (t.equals("*")) s.push((Integer)s.pop() * (Integer)s.pop());
else s.push(Integer.parseInt(t));
}
System.out.println(s.pop());
}

Categories

Resources