I am trying to make a calculator. It requires I use a string Tokenizer. I have done so fine with the numbers but can't figure out how to put the & and / in there. The input is supposed to be as follows

These are improper fractions whole & numerator / denominator.

2&6/8 - 1&1/8 (no space in between.) How can I make it ignore the '&' and '/' and give me just the numbers.

Here is me code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Torbecire
 */
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class Calculator {

    public String nextToken(String separators) {
        String ch = "&,/";
        StringTokenizer strToken;
        strToken = new StringTokenizer (",");
        strToken.nextToken("&/ ");
        return strToken.nextToken();
    }
    public static void main(String [] args)
    {
        BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
        String oneLine;
        StringTokenizer str;
        int x;
        int y;
        int z;
        String q;
    
        System.out.println("Enter a fractional problem:");
        try
        {
            oneLine = in.readLine();
            if( oneLine == null)
                return;
            
            str = new StringTokenizer( oneLine);
            if( str.countTokens() != 3)
            {
                System.out.println(" NEED 3 INTS");
                return;
            }
            x = Integer.parseInt( str.nextToken());
           // String q = /*str.nextToken() + */ "&" + str.nextToken();
            y = Integer.parseInt( str.nextToken());
           // String w = /*str.nextToken() + */ "/" + str.nextToken();
            z = Integer.parseInt( str.nextToken());
            System.out.println("Max: " + Math.max(x, y));
        }
        catch(IOException e)
        { System.err.println("Unexpected IO error"); }
        catch( NumberFormatException e)
        { System.err.println("Error: need two ints"); }
    }
    
}

Recommended Answers

All 6 Replies

Hi, torbecire....
I understand ur prob, so that I am sending u coding for calc.
Please let me know for further help.
Hope it will help u.

import java.io.*;                 //import the java.io package 

class calc 
{
     public static void main ( String [] args ) throws IOException     //throw any exceptions
     {
          BufferedReader stdin =  new BufferedReader(new InputStreamReader( System.in ));

            System.out.print( " Enter integer a  " );
            String input   =   stdin.readLine();             //get integer a
            int a    =   Integer.parseInt( input );

            System.out.print( "Enter integer b  " );
            input   =   stdin.readLine();                      //get integer b
            int b    =   Integer.parseInt( input );

            System.out.print( "     Enter your choice:  \n
                                          1. Addition             \n 
                                          2. Subtraction         \n 
                                          3. Multiplication       \n
                                          4. Division               \n");

            //Display the menu in the previous line

            input        =  stdin.readLine();         //get the choice of the user
            int choice  =  Integer.parseInt( input );

            switch( choice )                         //switch to the value of choice
        {
        case 1:                                //if choice is 1 then:
        System.out.println( a +" + "+ b + " = " + (a+b) );
        break;

        case 2:                                //if choice is 2
        System.out.println( a + " - " + b +" = " + (a-b) );
        break;

        case 3:                                 //if choice is 3
        System.out.println( a + " * " + b +" = " + (a*b) );
        break;

        case 4:                                 //if choice is 4
        System.out.println( a + " / " + b +" = " + (float)(a/b) );    
                 break;

                 //convert the result to float in the previous expression because a/b may not be a whole number always


        default:                                //if the user enters any other value
        System.out.println( "Enter a valid choice..." );

            }
      }                                                    // end main method

}                                                          // end calc
commented: That was not the question and even if it were, sending completed code to hand in for an assignment is not what this forum is about. -1

Hi,
actually what I want to do is input a string like
"2&5/3 - 3&3/9" and tokenize it to give me the integers and the operator ' - '. Could you tell me how to do that.
The 2 would be the whole, 3 denominator and 5 numerator same goes for the other mixed fraction
Thanks.

StringTokenizer is considered a legacy class now and it is recommended to use String.split(java.lang.String) or the java.util.regex classes for this now.

With split() you could first split on the math operator, giving you the two operand strings, and then spilt those into the whole and fractional strings, and then split the fractional into it's numerator and denominator. The one issue you may face doing that is your fraction separator "/" is the same as the division operator "/". If you can be certain that the operator will have blank spaces on both sides, it becomes much easier.

Give that a try and see how it goes. Even if you must use StringTokenizer due to some professor insisting you use legacy classes (does he know it's a legacy class?), still it may help if you consider that you don't have to parse the string in one shot from left to right. You can parse it into separate pieces and then parse those pieces into other pieces and so on, which can make the problem much cleaner to approach.

commented: good tip +1

o.k. I have done most of what I wanted now my only challenge is to some how get the operator (+,-,*,%) from the string and parse it as a char. If u know how to do this please tell me. The values will be entered like 2&4/9 - 1&5/5. THANKS

import java.util.*; 
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
 class ParseString 
    {   
   public static void main  ( String [] args  )   
    {
       BufferedReader in = new BufferedReader( new InputStreamReader(System.in));

  Scanner stdin = new Scanner(System.in);
System.out.println("Enter several integers separated by &, /, spaces");
String input = stdin.nextLine();

String delims = "&/-*%+ ";
StringTokenizer st = new StringTokenizer(input, delims);

    int x = Integer.parseInt(st.nextToken());
    int y = Integer.parseInt(st.nextToken());                   
    int z = Integer.parseInt(st.nextToken());
    int x2 = Integer.parseInt(st.nextToken());
    int y2 = Integer.parseInt(st.nextToken());                   
    int z2 = Integer.parseInt(st.nextToken());
    
    int h = x * y;
    int u = x2 + y2;
    System.out.println(x);
    System.out.println(z);
    System.out.println(y);
    System.out.println(x2);
    System.out.println(z2);
    System.out.println(y2);
    System.out.println(h);
    System.out.println(u);
    }   
    }

You can return your delimiters from the StringTokenizer by adding a third parameter when you create the tokenizer object.

StringTokenizer st = new StringTokenizer( input, delims, true );

Now your nextToken calls will return the delimiters as tokens as well. This will require changing how many calls you make in the next section of your code.
When you get each delimiter you can parse it to a char very easily:

// since we know the delimiter token has a length of 1
char del = ( st.nextToken() ).charAt( 0 );

P.S. Unless your assignment specifies that you must use a StringTokenizer, you really should listen to Ezzaral's advice...

Thanks for all the help. It solved my problem.

Yes I did need to use the String Tokenizer. May be we will use the split one day.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.