0

I am developing a simple calc my input 3+3

I can do it with spaces(3 + 3) but how can I do it without spaces like (3+3)!

this my last code I know it was wrong but I still learning !

package calcPkg;

import java.util.Scanner;
import java.util.StringTokenizer;

public class test {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        String myString = input.nextLine();
    String DELIM     = "+";
        double dblNum1   = 0;
        double dblNum2   = 0;
        double dblResult = 0;

        StringTokenizer st = new StringTokenizer(myString, DELIM, true);

        dblNum1 = Double.parseDouble(st.nextToken());
        //dblNum2 = Double.parseDouble(st.nextToken());

        dblNum2 = 2;
        dblResult = dblNum1 + dblNum2;

        while (st.hasMoreTokens())
            System.out.println(st.nextToken());


        System.out.println("First Number:" + dblNum1);
        System.out.println("Operation:" + DELIM);
        System.out.println("Second Number:" + dblNum2);
        System.out.println("Result:" + dblResult);

    }
}
max
  • 96,212
  • 14
  • 104
  • 165

2 Answers2

1

I'm guessing your problem was dealing with spaces, you don't need StringTokenizer to return you the '+', so you don't need the third argument of StringTokenizer, once you get your tokens you can simply trim the white spaces using the trim() function for strings

public class Test {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String myString = input.nextLine();
        String DELIM     = "+";

        StringTokenizer st = new StringTokenizer(myString, DELIM);
        double dblNum1 = Double.parseDouble(st.nextToken().trim());
        double dblNum2 = Double.parseDouble(st.nextToken().trim());

        double dblResult = dblNum1 + dblNum2;

        System.out.println("First Number:" + dblNum1);
        System.out.println("Operation:" + DELIM);
        System.out.println("Second Number:" + dblNum2);
        System.out.println("Result:" + dblResult);

    }
}

I wrote the addition part for you but I'm guessing your expected to write the full +,-,*,/ arithmetic calculator so you can finish that based on what you see here, the DELIM however will be assigned using conditional, if or switch statements in java so you should look those up.

Mauricio Trajano
  • 2,677
  • 2
  • 20
  • 25
0

I just had the same problem and solved it using Script Engine.

Just ensure your application handles malicious scripts, by checking if variables inputted are valid etc...

Evaluating a math expression given in string form

Community
  • 1
  • 1
javapadawan
  • 897
  • 6
  • 12
  • 29