Home arrow static arrow Java Programming [Archive] - Code without try-catch, just if/else...
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Code without try-catch, just if/else...
This topic has 10 replies on 1 page.

Posts:74
Registered: 11/20/03
Code without try-catch, just if/else...  
Jun 14, 2004 6:43 PM



 
Hi,
I'm trying to change some code in an exercise I'm doing and having some trouble. I have a small calculator and I needed it to check for integers as input and prompt the user if their input was incorrect but without using try-catch... just using if/else or something like that.

So it has to check for the Integer, and if a negative number was entered, handle that too. I had got some previous help but I just realized it was not completely the way I need it.

If you see the code below, you'll I'm on the last part trying to replace the code in the "private static boolean isInteger(String s) {" section with the "public static boolean isDigit(char ch) {" and the statements thayt follow........

I found some code on the net (you can see below I commented out the stuff I'm trying to change and then tried to put in the code I found I thought might work below it)..... but I can't seem to get to work.

Could someone please give me a hand fixing this?? It would be appreciated... thank you.

public class calc {/**Main method*/   public static void main(String[] args) {      //check command line arguements      if (args.length == 3) {  //3 args needed          if( isInteger(args[1]) && isInteger(args[2]) ) process(args); //check if both integers          else {	          //printout warning for not both integers             System.out.println("Invalid integer argument --> operand1 and operand2 must be integers\n Usage: java calc operator operand1 operand2");            System.exit(0);  //kill thread         }      }else {		//printout for wrong syntax entered	     System.out.println("Usage: java calc operator operand1 operand2");         System.exit(0);      }   }   private static void process(String[] args){      //the result of the operation      int result = 0;      //determine the operator         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 result      System.out.println(args[1] + ' ' + args[0] + ' ' + args[2]+ " = " + result);   }      //private static boolean isInteger(String s) {       //boolean isValid = true;       //try{ Integer.parseInt(s); }       //catch(NumberFormatException nfe){ isValid = false; }       //return isValid;           public static boolean isDigit(char ch) { 	public String getInteger() {  //throws IOException {	StringBuffer sbuff = new StringBuffer();	int ch = read(); 	while ((ch != -1) && Character.isWhitespace((char)ch)) {	    ch = read();	} 	if ((ch != -1) && ((char)ch == '-')) {	    sbuff.append((char)ch);	    ch = read();	} 	while ((ch != -1) && Character.isDigit((char)ch)) {	    sbuff.append((char)ch);	    ch = read();	} 	unread(ch);	return sbuff.toString();    }          } } 
 

Posts:1,183
Registered: 1/23/02
Re: Code without try-catch, just if/else...  
Jun 14, 2004 6:58 PM (reply 1 of 10)



 
I would start by throwing away isDigit(), which is a load of nonsence. Half of your problem is defining what is an integer. Presumably you consider the following integers:

27
-3
0

What about

00
-0
--1
30.0
10E04
3,123,456
0xF7F4
2147483648
0000000001

?

The one before last is particularly tricky to deal with. Once you define clearly what is an integer you can write an isInteger(String) method without try..catch.
 

Posts:74
Registered: 11/20/03
Re: Code without try-catch, just if/else...  
Jun 14, 2004 7:07 PM (reply 2 of 10)



 
I would start by throwing away isDigit(), which is a
load of nonsence. Half of your problem is defining
what is an integer. Presumably you consider the
following integers:
The one before last is particularly tricky to deal
with. Once you define clearly what is an integer you
can write an isInteger(String) method without
try..catch.

Legosa,

It's just a simple calculator with - + / * .... the point is more understanding how to do it with vs without use of try-catch so assume like -100 to 100 maybe........theres not gonna be any crazy entries like u asked about, just simple stuff... 25 * 25, -4 - 10, 81/9, -2 + 17......stuff like that.........

It was suggested to use isDigit so its expecting simplicity......

Can you please assist me based on that?
 

Posts:1,183
Registered: 1/23/02
Re: Code without try-catch, just if/else...  
Jun 14, 2004 7:13 PM (reply 3 of 10)



 
Like I said, forget isDigit(), it's a bit of a mess :-)

Let's start again. We will write a method public boolean isInteger(String s), which will return true iff the argument is between 1 and 5 characters long and all characters are decimal digits, with the exception that the first character may be a minus sign.

More to come...
 

Posts:1,183
Registered: 1/23/02
Re: Code without try-catch, just if/else...  
Jun 14, 2004 7:15 PM (reply 4 of 10)



 
public boolean isInteger(String s) {    if (s.length() < 1 || s.length() > 5) {        return false;    }    // Next test here...}
 

Posts:1,183
Registered: 1/23/02
Re: Code without try-catch, just if/else...  
Jun 14, 2004 7:17 PM (reply 5 of 10)



 
public boolean isInteger(String s) {    if (s.length() < 1 || s.length() > 5) {        return false;    }    for (int i = 1; i < s.length() i++) {        if (!Character.isDigit(s.charAt(i))) {            return false;        }    }    // Can you come up with the final test?}
 

Posts:74
Registered: 11/20/03
Re: Code without try-catch, just if/else...  
Jun 14, 2004 7:48 PM (reply 6 of 10)



 
public boolean isInteger(String s) {if (s.length() < 1 || s.length() > 5) {return false;}for (int i = 1; i < s.length() i++) {if (!Character.isDigit(s.charAt(i))) {return false;}}// Can you come up with the final test?}

argggggghhhhhhhhh......... I can't get my flipping mind to think straight,,,,,,,,,,, ok, you did a check of between 1 & 5 digits... then you checked if its not a digit (for negative numbers) right?

soooooo.......... next would be, if the first number is a digit, assign that digit to variable of some sort?? So you can go thru all the digits of the number?

String x = i + .......... no thats not right, or is it..............uhmm..... i'm trying to think........
 

Posts:1,183
Registered: 1/23/02
Re: Code without try-catch, just if/else...  
Jun 14, 2004 8:02 PM (reply 7 of 10)



 
then you checked if its not a digit (for negative numbers) right?

Nope, read the loop carefully. It goes through each character of the input from the second character to the end (remember, the first character has index i = 0). If any of of those characters is not a digit the loop immediately returns "false" - we know the input can't be a valid integer.

The reason why the loop goes from the second character is that the first one needs to be treated specifally. It may be a digit, in which case all characters are digits and we can return "true". Or it may be the minus sign, in which case we return "true", provided minus is not the only character in the input.

Wanna give it another shot?
 

Posts:74
Registered: 11/20/03
Re: Code without try-catch, just if/else...  
Jun 14, 2004 8:16 PM (reply 8 of 10)



 
then you checked if its not a digit (for negative
numbers) right?

Nope, read the loop carefully. It goes through each
character of the input from the second
character
to the end (remember, the first
character has index i = 0). If any of of those
characters is not a digit the loop immediately returns
"false" - we know the input can't be a valid integer.

The reason why the loop goes from the second character
is that the first one needs to be treated specifally.
It may be a digit, in which case all characters are
digits and we can return "true". Or it may be the
minus sign, in which case we return "true", provided
minus is not the only character in the input.

Wanna give it another shot?

ok, so if it checks 2 thru 5 then............. I'd be checking if the first digit and checking if it is a minus sign?

Something kinda like this (although I'm sure thats not right)?......

elseif (s.length() = 0 && ((char)ch == '-')) {return true;
 

Posts:1,183
Registered: 1/23/02
Re: Code without try-catch, just if/else...  
Jun 14, 2004 8:35 PM (reply 9 of 10)



 
One gets the sense you aren't thinking very hard about it. :-(
public boolean isInteger(String s) {    if (s.length() < 1 || s.length() > 5) { // Allow input between 1 and 5 characters long        return false;    }    for (int i = 1; i < s.length() i++) { // Check that all characters beyond the first are digits        if (!Character.isDigit(s.charAt(i))) {            return false;        }    }    // Allow the first character to be a digit, or a minus sign provided it's not the only character    return Character.isDigit(s.charAt(0)) || ((s.charAt(0) == '-') && s.length() > 1);}
 

Posts:74
Registered: 11/20/03
Re: Code without try-catch, just if/else...  
Jun 14, 2004 8:59 PM (reply 10 of 10)



 
One gets the sense you aren't thinking very hard about
it. :-(
public boolean isInteger(String s) {if (s.length() < 1 || s.length() > 5) { // Allow inputbetween 1 and 5 characters longreturn false;}for (int i = 1; i < s.length(); i++) { // Check thatall characters beyond the first are digitsif (!Character.isDigit(s.charAt(i))) {return false;}}// Allow the first character to be a digit, or a minussign provided it's not the only characterreturn Character.isDigit(s.charAt(0)) || ((s.charAt(0)== '-') && s.length() > 1);}

legosa,

I'm sorry man, I really am trying.... :-( ....... it's almost midnight here and I've been up since 6:00am & I worked 9-5pm so I'm a bit on the tired side which is likely hurting my thought processes :-(

I'm getting a "class or interface expected" on the last 2 "}" in my code so I must have mixed up a bracket somewhere assuming your syntax is correct (I added a ";" you omitted in the for loop)...........

I guess I should look at this tomorrow with a fresh mind .......... Should everything you showed me to now the whole enchilada??

Thank you for your help up to this point.

 
This topic has 10 replies on 1 page.