aspose file tools*
The moose likes Cattle Drive and the fly likes convert string to an int Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » This Site » Cattle Drive
Bookmark "convert string to an int" Watch "convert string to an int" New topic
Author

convert string to an int

Ray Marsh
Ranch Hand

Joined: Jan 12, 2000
Posts: 458
Assignment 1.2 runs fine if an integer is entered, however, if letters or decimal values are entered I get this:java.lang.NumberFormatException: 1.5
at java.lang.Integer.parseInt(Compiled Code)
at java.lang.Integer.parseInt(Integer.java:458)
at EvenOdd.main(EvenOdd.java:4)
What to do? Here's my code.public class EvenOdd
{
public static void main(String[] args) {

// Convert String "args[0] to an int
int x = Integer.parseInt( args[0] );
// Perform modulo: divide by 2 and capture the remainder in int r
int r = x % 2;
// If the input is an even integer the remainder ( int r ) will be zero
if( r == 0 )
{
System.out.println("even");
}
// If the input is an odd integer the remainder will not be zero
else
{
System.out.println("odd");
}
}
} ///:~
Thanks.

Anxiety does not empty tomorrow of its sorrows, but only empties today of its strength. – Charles Spurgeon
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20582
    ∞

Well, you called parseInt and the string didn't contain just an int. So it threw an exception so you could handle this problem if you wanted to.
Don't worry about it. Just feed in whole numbers to your program for now.

permaculture Wood Burning Stoves 2.0 - 4-DVD set
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: convert string to an int