aspose file tools*
The moose likes Beginning Java and the fly likes String arguments Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String arguments" Watch "String arguments" New topic
Author

String arguments

Marie Jeanne Thibault
Greenhorn

Joined: Nov 15, 2003
Posts: 15
I'm really stuck. I only want this program accept integer input. Any other input like a char I want it to display a message that it is the wrong type of input and display the input in question. Here is what I've got so far. Any help would be appreciated.
Thanks,
Marie
//ExceptDemo1b.java
public class ExceptDemo1b
{
//Main Method with three arguments
//args[0]: operator
//args[1]: operand1
//args[2]: operand2
public static void main(String[] args)
{
//Declare and initialize variables
int result = 0;
int operand1 = 0;
int operand2 = 0;
if (args.length != 3)
{
System.out.println("Usage: java Calculator operator operand1 operand2");
System.exit(0);
}
if(((operand1 >= 0) || (operand1 < 0)) && ((operand2 >= 0) || (operand2 < 0)))
{
operand1 = Integer.parseInt(args[1]);
operand2 = Integer.parseInt(args[2]);
switch (args[0].charAt(0))
{
case '+': result = Integer.parseInt(args[1]) +
Integer.parseInt(args[2]);
break;
case '-': result = Integer.parseInt(args[1]) -
Integer.parseInt(args[2]);
break;

case '*': result = Integer.parseInt(args[1]) *
Integer.parseInt(args[2]);
break;
case '/': result = Integer.parseInt(args[1]) /
Integer.parseInt(args[2]);
}
//Display the result
System.out.println(args[1]+ ' ' +args[0]+ ' ' +args[2]+ "=" +result);
}
else
{
System.out.println("Wrong input ");
System.exit(0);
}

}
}
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Hi Marie,
Welcome to JavaRanch. Well, this stuff is always kinda tricky. First, you should probably try a divide and conquer strategy on the usage. Set up some constants for the usage strings and exit codes (by Unix standards you shouldn't exit 0 on an exceptional event) and create some private methods to actually print the message and exit for you when something bad happens. We Java programmes use a little trick to verify numeric input buy wrapping the parse methods in a try/catch for NumberFormatException. Take a look at this and see if it makes sense to you, if not ask some more questions:


Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671

I'm curious, what do you want this line to do? Whatever it is, I suspect that you should study this expression carefully - it probably doesn't do what you think it does.


"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String arguments