简体   繁体   中英

Java console calculator using StringTokenizer

I'm trying to make a calculator (code only) using StringTokenizer , but I'm lost. I have to make the calculator with the possibilities to do the simple maths (+-*) and some other not so basic operations (log, sin, tan, exponential). This code is an example with the basic maths - I wanted to do with the basics first, and then add the other functions using methods.

However, I don't know how to make the operations, I was thinking that maybe a switch could do the job, but with BEMDAS it gets complicated. The code above only puts the operands in a char array, and the numbers in a double array, then I didn't know how to continue. If some one can explain me how to continue this, or guide me, I will appreciate it.

import java.util.StringTokenizer;
import java.io.*;

public class Calculator  {
  public static void main (String[] args) {     
    int i=0;
    int j=0;
    int n=0;
    int o=0;
    double num []= new double [100];
    char op[]=new char [100];
    String ops[]=new String [100];

    String x = "5*10+15/12";
    StringTokenizer st = new StringTokenizer(x, "*/-+", true);
    while(st.hasMoreTokens()){
      ops[j] =st.nextToken();
      j++;
    }

    for(i=0; i<j;i++){
      if(i%2==0){
        num[n]=Double.parseDouble(ops[i]);
        n++;
      }
      else{
        op[o]=ops[i].charAt(0);
        o++;
      }
    }

    for(i=0; i<n;i++)
      System.out.println(num[i]);

    for(i=0; i<o;i++)
      System.out.println(op[i]);
  }
}

First you have to think abstractly, you have to think of a process to solve the problem. How do YOU solve "5*10+15/12"? How were you taught to break the problem down in grade school? Think about how you break the problem down into simple steps in your own head. You will be able to translate this process in your head into loops, structures, if statements, trees and algorithms.

First off, the "ops" variable never gets assigned to anything, so your while loop is doing nothing. The first thing you need to think about is how to get the operations, in this case, the asterisk, plus, and divide from this string: "5*10+15/12" into that opts variable so you can loop through them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM