将字符串转换为int时的NumberFormatException

时间:2017-02-16 17:13:13

标签: java

import java.util.*;
class abc
{
public static void main(String[] args)
{
    int sum=0,n=4,k=10,i,j;
    char ch[] = new char[10];
    char ans[] = new char[19];
    Scanner sc = new Scanner(System.in);
    try1 abc=new try1(); 
 String a,b,c,d;
 a= sc.nextLine();
 b= sc.nextLine();
 c= sc.nextLine();
 d= sc.nextLine();
 int num1 = (int) Long.parseLong(a,16);
 int num2 = (int) Long.parseLong(b,16);
 int num3 = (int) Long.parseLong(c,16);
 int num4 = (int) Long.parseLong(d,16);

 sum = num1 + num2 + num3 + num4;
 String sumstart = Integer.toHexString(sum);
 System.out.println(sumstart);
 String temp=sumstart;
 ch = temp.toCharArray();   
 for ( i=1, j=0;i<5;i++,j++)
 {
    ans[j] = ch[i];
    }   
    ans[j]='\0';
    System.out.println(ans);
     String anssing = Integer.toHexString(ch[0]);
      int num5 = (int) Long.parseLong(anssing,16);
      String ans1 = new String(ans);

       System.out.println("ans 1  "+ans1);

      int num6 =abc.convert(ans1);
       System.out.println("num 6 vaala "+num6);
      int ans2 = num5 + num6;
      String hex4 = Integer.toHexString(ans2);
      System.out.println("hex4 vaala "+hex4);

}
}
class try1
{
  int convert(String a)
    {

    int num5 = Integer.parseInt("3f18",16);
    System.out.println(num5);
    return num5;
    }
}   

考虑任何输入,例如

8fc6
8fc6
8fc6
8fc6

输出:

Numberformatexception

我在char数组中存储了十六进制数,然后我将其转换为String,现在我尝试将其转换为整数,但我收到了NumberFormatException。任何人都可以帮我解决吗?

1 个答案:

答案 0 :(得分:-1)

试试这个,

import java.util.*;
class abc
{
public static void main(String[] args)
{
    int sum=0,n=4,k=10,i,j;
    char ch[] = new char[10];
    char ans[] = new char[19];
    Scanner sc = new Scanner(System.in);
    try1 abc=new try1(); 
 String a,b,c,d;
 a= sc.nextLine();
 b= sc.nextLine();
 c= sc.nextLine();
 d= sc.nextLine();
 int num1 = Integer.parseInt(a,16);
 int num2 = Integer.parseInt(b,16);
 int num3 = Integer.parseInt(c,16);
 int num4 = Integer.parseInt(d,16);

 sum = num1 + num2 + num3 + num4;
 String sumstart = Integer.toHexString(sum);
 System.out.println(sumstart);
 String temp=sumstart;
 ch = temp.toCharArray();   
 for ( i=1, j=0;i<5;i++,j++)
 {
    ans[j] = ch[i];
    }   
    ans[j]='\0';
    System.out.println(ans);
     String anssing = Integer.toHexString(ch[0]);
      int num5 = (int) Long.parseLong(anssing,16);
      String ans1 = new String(ans);

       System.out.println("ans 1  "+ans1);

      int num6 =abc.convert(ans1);
       System.out.println("num 6 vaala "+num6);
      int ans2 = num5 + num6;
      String hex4 = Integer.toHexString(ans2);
      System.out.println("hex4 vaala "+hex4);

}
}
class try1
{
  int convert(String a)
    {

    int num5 = Integer.parseInt("3f18",16);
    System.out.println(num5);
    return num5;
    }
}   

说明:我已添加Integer.parseInt来解析String输入以避免NumberFormatException