Avatar of Mike Eghtebas
Mike EghtebasFlag for United States of America

asked on 

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

Java

Avatar of undefined
Last Comment
for_yan
Avatar of for_yan
for_yan
Flag of United States of America image

but you hva case 'm' rather than case '*' - ?
Avatar of for_yan
for_yan
Flag of United States of America image

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

Avatar of for_yan
for_yan
Flag of United States of America image

* uis a special smbol in the argument list
Avatar of for_yan
for_yan
Flag of United States of America image

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.
Avatar of for_yan
for_yan
Flag of United States of America image

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
Avatar of for_yan
for_yan
Flag of United States of America image

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
Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

ASKER

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
Avatar of for_yan
for_yan
Flag of United States of America image

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
Avatar of for_yan
for_yan
Flag of United States of America image

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

Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

ASKER

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.
Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

ASKER

re:> 6.0 " \\*"  3

I get:

unbalanced quotes in 41 "\\*"' 8
Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

ASKER

sorry sorry, I get:

41 \\* 8 = 0

with 6.0 " \\*"  3
Avatar of for_yan
for_yan
Flag of United States of America image

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


Avatar of for_yan
for_yan
Flag of United States of America image

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 "\\*"

Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

ASKER

I can see your point on using 6 vs 6.0

But I am not sure why 6 "*" 3 is not working.
Avatar of for_yan
for_yan
Flag of United States of America image

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

Avatar of for_yan
for_yan
Flag of United States of America image

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


Avatar of for_yan
for_yan
Flag of United States of America image

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
Avatar of for_yan
for_yan
Flag of United States of America image


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


Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

ASKER

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
Avatar of for_yan
for_yan
Flag of United States of America image

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
Avatar of for_yan
for_yan
Flag of United States of America image

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
Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

ASKER

here it is:
Java.png
Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

ASKER

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
Avatar of for_yan
for_yan
Flag of United States of America image

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
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of for_yan
for_yan
Flag of United States of America image

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
Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

ASKER

thank you
Avatar of for_yan
for_yan
Flag of United States of America image

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
 
Java
Java

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

102K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo