java中的数据类型转换错误

时间:2016-11-29 23:36:32

标签: java type-conversion

出现意外错误

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 : 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)

1 个答案:

答案 0 :(得分:0)

这是有问题的一行:int number1 = Integer.parseInt(word) ;

word是非数字字符串;代码试图将其转换为Integer,但它无法做到。您可能希望打印出来自input的每件事,并确保您拥有自己的想法。

祝你好运。