This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

convert string to an int

 
Ray Marsh
Ranch Hand
Posts: 458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
paul wheaton
Trailboss
Pie
Posts: 21385
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic