Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Calculator... args[]

Posted on 2011-10-02
29
Medium Priority
?
296 Views
Last Modified: 2013-11-23
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

0
Comment
Question by:Mike Eghtebas
  • 20
  • 9
29 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36900767
but you hva case 'm' rather than case '*' - ?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36900775
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36900778
* uis a special smbol in the argument list
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 47

Expert Comment

by:for_yan
ID: 36900780
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36900789
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36900808
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
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36900819
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36900822
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36900833
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
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36900861
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
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36900864
re:> 6.0 " \\*"  3

I get:

unbalanced quotes in 41 "\\*"' 8
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36900867
sorry sorry, I get:

41 \\* 8 = 0

with 6.0 " \\*"  3
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36900870
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36900877
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
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36900878
I can see your point on using 6 vs 6.0

But I am not sure why 6 "*" 3 is not working.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36900887
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36900891
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36900903
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36900912

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
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36900937
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36900947
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36900950
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
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36900955
here it is:
Java.png
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36900965
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36900967
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
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 36900969

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

Expert Comment

by:for_yan
ID: 36900974
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
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 36900975
thank you
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36900991
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

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

580 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question