Calculator... args[]

In the following calculator code I have two problems:

1. The acceptable list of arguments are:

6 + 3
6 - 3
6 "*" 3
6 / 3

All work except  6 "*" 3.

2. Also, when I am 6.0  + 3, for example it fails despite the fact I cast them to integer before they are used like in:

result=Integer.parseInt(args[0]) + Integer.parseInt(args[2]);

Question: Can you figure out what is taking place with items 1 and 2 described above?

Thank you.
public class Calculator {
    
    public static void main(String[] args) {
        
        if (args.length !=3) {
            System.out.println(
                    "Usage: java Calculator operand1 operator operand2\n");
            
            System.exit(0);
        }
        
        
        int result=0;
        
        
        switch (args[1].charAt(0)){
            case '+': result=Integer.parseInt(args[0]) +
                             Integer.parseInt(args[2]);
                      break;
            case '-': result=Integer.parseInt(args[0]) -
                             Integer.parseInt(args[2]);
                      break;
            case 'm': result=Integer.parseInt(args[0])*
                             Integer.parseInt(args[2]);
                      break;
            case '/': result=Integer.parseInt(args[0]) /
                             Integer.parseInt(args[2]);
        }
        
        System.out.print(args[0]+' '+ args[1]+' '+args[2]
                +" = "+result+"\n");
    }
}

Open in new window

LVL 34
Mike EghtebasDatabase and Application DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

for_yanCommented:
but you hva case 'm' rather than case '*' - ?
0
for_yanCommented:
public class Calculator {

    public static void main(String[] args) {

        if (args.length !=3) {
            System.out.println(
                    "Usage: java Calculator operand1 operator operand2\n");

            System.exit(0);
        }


        int result=0;


        switch (args[1].charAt(0)){
            case '+': result=(int) Double.parseDouble(args[0]) +
                             Integer.parseInt(args[2]);
                      break;
            case '-': result=Integer.parseInt(args[0]) -
                             Integer.parseInt(args[2]);
                      break;
            case 'm': result=Integer.parseInt(args[0])*
                             Integer.parseInt(args[2]);
                      break;
            case '/': result=Integer.parseInt(args[0]) /
                             Integer.parseInt(args[2]);
        }

        System.out.print(args[0]+' '+ args[1]+' '+args[2]
                +" = "+result+"\n");
    }
}

Open in new window

0
for_yanCommented:
* uis a special smbol in the argument list
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

for_yanCommented:
check here about asterisk
http://www.codestyle.org/java/faq-CommandLine.shtml

Q: When I pass *.java as an argument I get a list of all my source files!

    A: The behaviour you are seeing is a consequence of the way the system shell interprets the asterisk as a so called "wildcard" operator that represents a set of files. This is intended as a convenience because it is an easy way to pass a series of file names as arguments to a program such as the Java interpreter. Putting a partial file path before the asterisk, or a file extension after it makes the file listing more specific, but you cannot alter the fundamental behaviour.

    To limit this behaviour, enclose any argument that contains an asterisk in double quotes, to ensure it is not expanded to a series of file names. An alternative is to omit the asterisk in the command line and write your program in such a way that the asterisk is implicit and add it to the input arguments where applicable.
0
for_yanCommented:
if you use "x" for multipiliction it will work fine

and about Integer.parseInt(6.0) -it does not allow dot in there - so do as i did - use Double.parseDouble and then cast the result to int
0
for_yanCommented:
Windows command line expands * (even when I put it in double quotes) into the list of files ion the current folder and send all file names
as the command line arguments
0
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
re:> case 'm': res...

I was trying to use +, -, m, and / but decided to go back to the instruction and use *.

The book says "*" should do it but it doesn't work. I have not read all of you post yet. reading now.

brb
0
for_yanCommented:
I guess if you want to use asterisk for multiplication then you would want to change the program and
request that you whoile string should be input as one argument in double quotes, like
"6.0 * 3" or "6.0 + 3" - then you can parse into  operand - operation - operand withing your program
Then asterisk "6.0 * 3" would work

Alternatively you can input asterisk with two backslahses

6.0 " \\*"  3

but then you should check not the first charcater as Java passes all three chars to "\\*" to the program
0
for_yanCommented:
if you use this code below and run it

java Calculator 6.0 * 3

you'll see that you get the list of all files in the default folder as your
args array elements
 
public class Calculator {

    public static void main(String[] args) {

        for(String s: args){
            System.out.println(s);
        }

        if (args.length !=3) {
            System.out.println(
                    "Usage: java Calculator operand1 operator operand2\n");

            System.exit(0);
        }


        int result=0;


        switch (args[1].charAt(0)){
            case '+': result=(int) Double.parseDouble(args[0]) +
                             (int) Double.parseDouble(args[2]);
                      break;
            case '-': result=Integer.parseInt(args[0]) -
                             Integer.parseInt(args[2]);
                      break;
            case 'x': result=(int)Double.parseDouble(args[0])*
                             (int) Double.parseDouble(args[2]);
                      break;
            case '/': result=Integer.parseInt(args[0]) /
                             Integer.parseInt(args[2]);
        }

        System.out.print(args[0]+' '+ args[1]+' '+args[2]
                +" = "+result+"\n");
    }
}

Open in new window

0
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
I have copied Calculator.java from a book. I want to be able to duplicate the solution. All works fine except the two items I have described.

But, when I supply argument like

6 "*" 3

It doesn't work. I am sure there are many ways like using x etc in place of *. But I am interested to do and duplicate what the book says.

Also, when I use:

6.0 + 3

it gives error.

These two items are what I am interested in.  BTW, I corrected back to

case '*': result=(int)Double.parseD

So, any solution in these two areas?

Thank you. Will read the link next.
0
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
re:> 6.0 " \\*"  3

I get:

unbalanced quotes in 41 "\\*"' 8
0
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
sorry sorry, I get:

41 \\* 8 = 0

with 6.0 " \\*"  3
0
for_yanCommented:
look above how to deal with 6.0

If you want to use numbers with dots you need to do everything in double - ake your result double and
and make all double , otherwise you can do the way I showed

 case '+': result=(int) Double.parseDouble(args[0]) +
                            (int) Double.parseDouble(args[2]);

but this is not very good as you'll be incorrecty if they enter 6.5 etc,.
thsi calculator as it was written is only for integer
numbers and cannot be used for double in this form


0
for_yanCommented:
Your book unfortunatel gave bad example - you cannot use asterisk - I wrote above what are your options - you can either imnput everything in quotes
"6 * 3" and parse args[0]

or you can use

6 \\* 3 and then

args[1].charAt(0)) will not work as it will give you cahr '\' so you need to change operand to "*" within the program when it is "\\*"

0
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
I can see your point on using 6 vs 6.0

But I am not sure why 6 "*" 3 is not working.
0
for_yanCommented:
This is the way you can make it work with

java Calculator 6 \\* 3

public class Calculator {

    public static void main(String[] args) {

        for(String s: args){
            System.out.println(s);
        }

        if (args.length !=3) {
            System.out.println(
                    "Usage: java Calculator operand1 operator operand2\n");

            System.exit(0);
        }


        int result=0;

        if(args[1].equals("\\\\*"))args[1]= "*";
        System.out.println(args[1].charAt(0));

        switch (args[1].charAt(0)){
            case '+': result=(int) Double.parseDouble(args[0]) +
                             (int) Double.parseDouble(args[2]);
                      break;
            case '-': result=Integer.parseInt(args[0]) -
                             Integer.parseInt(args[2]);
                      break;
            case '*': result=(int)Double.parseDouble(args[0])*
                             (int) Double.parseDouble(args[2]);
                      break;
            case '/': result=Integer.parseInt(args[0]) /
                             Integer.parseInt(args[2]);
        }

        System.out.print(args[0]+' '+ args[1]+' '+args[2]
                +" = "+result+"\n");
    }
}

Open in new window


Output:
6.0
\\*
3
*
6.0 * 3 = 18

Open in new window

0
for_yanCommented:
asterisk is a special symbol

go to Windows dos command line window and type

dir *

You'll see that windows will print the list of the files in current directory


0
for_yanCommented:
Every time you type * on dos command line (with dir command or with java command - it does not matter )
the first thing operating system (Windows) is doing - it is replacing the asterisk with
the list of file names in the current diredctory

as a result  supposte you have in your fioolder files
list.txt
Cacluclator.java
 ...

then the forst thing windows does (befroe it even feeds the string to java and even before it caslls java.exe program) it expands your asterisk and
your command

java Calculator 6 * 3

becomes

java Calculator  6 list.txt Caclulator.java .... 3

so when java gets the arguments it sees

args[0] = "6";
args[1] = "list.txt";
args[2] = "Calculator.java";
args [3] = //next file name
args[4] = //next file name
...

args[n] = "3";

as a result you get your args.length much bigger than 3
and you get your Usage:... error message

becauise it happend even before your java program gets the line - there is not much you can do about it
0
for_yanCommented:

In my posting above:
ID:36900833Author

I posted the code which prints out all args values - if you run that
code with

java Calculator 6 * 3

you'll see in your output the listsing of all files in your current directory
after the arg[0] which is "6" nad before  "3" which is the last args element

This confirms my explanation in the post immediately above

All this is becasue asterisk has a very special meaning
for DOS


0
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
I guess 6 "*" 3 should work if I use C prompt not netbeans. The assumption the book is making we are using C prompt.

brb
0
for_yanCommented:
waht is C prompt ?

I used another IDE to dwebug it - not NetBeans but any IDE when you put in the Run configurations
command line argument should do exactly as the uunderlying system does,
If IDE does not do it - this is a bug with IDE, I doubt that NetBeans would do something else
0
for_yanCommented:
The other thing that it may depend on the target system - so if you are doing this
on Unix, maybe system behavior could be different and it would expand * only when it expects filename as the argument
- i doubt it in case of Unix though - I think unix Java will behave in the same mamanner as Windows java does
0
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
here it is:
Java.png
0
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
If we have:

String s= "10.0";

how can we store it in

int intNo = ...
double dblNo =...

so we could have

intNo = 10
dblNo = 10.0

thx
0
for_yanCommented:
Well, mybe my IDE was not truthful to what system does, but so it was for many systems where other people where tesrting it (see some of the quotes above)
Or maybe it depends on XP or Vista or whatever
0
for_yanCommented:

String s = "10.0";
dblNo = Double.parseDouble(s);
intNo = (int) dblNo;
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
for_yanCommented:
But with these operations of casting double to int one should be careful
beacuse if your s="10.5" or even s = "10.7"
then when you cast to int you'll lose the decimal part
and intNo will become  still 10
0
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
thank you
0
for_yanCommented:
Yes, you are right - on my actual command line
java Calculator 6 * 3
indeed takes the whole list of file names, wherea
java Calculator 6 "*" 3 works nicely

In the IDE it was taking  the lsit of file names in both cases

So indeed, IDE was not true to the system for some reason - I would think it is a flaw with IDE,
but indeed the case is rather special
 
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.