Java: String index out of range while checking if a number is a palindrome -
so, in order check if number palindrome converted string. know there similar question on have checked solution, appreciated. why "exception in thread "main" java.lang.numberformatexception:
?
my code here;
/* (palindrome integer) write methods following headers // return reversal of integer, i.e., reverse(456) returns 654 public static int reverse(int number) // return true if number palindrome public static boolean ispalindrome(int number) use reverse method implement ispalindrome. number palindrome if reversal same itself. write test program prompts user enter integer , reports whether integer palindrome. */ import java.util.scanner; public class test { public static void main(string[] args) { system.out.println("please enter number"); scanner input = new scanner(system.in); int number = input.nextint(); if (ispalindrome(number)) system.out.println("the number palindrome"); else system.out.println("the number not palindrome"); } public static int reverse(int number) { string reverse = ""; string n = number + " "; (int = n.length() - 1; >= 0; i--) { reverse += n.charat(i); } return integer.parseint(reverse); } public static boolean ispalindrome(int number) { return number == reverse(number) ? true : false; } }
the problem in reverse function. in fact instruction string n = number + " ";
concatenation of value number
blank string. not number , later on gives nomberformatexception @ instruction return integer.parseint(reverse);
. should use string n = integer.tostring(number);
here's reviewed method
public static int reverse(int number) { string reverse = ""; string n = integer.tostring(number); // + " "; system.out.println(reverse); (int = n.length() - 1; >= 0; i--) { reverse += n.charat(i); } return integer.parseint(reverse); }
Comments
Post a Comment