darkmatter darkmatter - 7 days ago 5
Java Question

Data Type conversion error in java

Getting unexpected error

import java.util.Scanner;

public class Solution {

public static void main(String[] args) {

Scanner input = new Scanner(System.in) ;
int number = input.nextInt() ;

String word = input.nextLine();

String word1 = Integer.toString(number) ;
int number1 = Integer.parseInt(word) ;

if (number1 == Integer.parseInt(word) )
{
number1 = number + 10 ;
System.out.println("Congratualtion its a number"+" "+ number1) ;
}

else if (word1 == Integer.toString(number) )
{ word1 = 10 + word ;
System.out.println("Congratualtion its a word"+" "+ word1);
}
else
System.out.println("Something is wrong !!! ") ;

}
}


Error message:

Error : Exception in thread "main" java.lang.NumberFormatException: For input string: " "
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at Solution.main(Solution.java:13)

Answer

This is the problematic line: int number1 = Integer.parseInt(word) ;

word is a non-numeric String; the code is trying to convert it to an Integer, which it cannot do. You might want to print out each thing you get from input and make sure you have what you think you have.

Good luck.