gpt4 book ai didi

java - 从 int 强制转换为 byte 会导致 --- 线程中出现异常 "main"java.lang.NumberFormatException

转载 作者:行者123 更新时间:2023-12-01 12:16:47 25 4
gpt4 key购买 nike

我正在编写一个程序,通过使用方法 InetAddress.getByAddress(byte[] addr) 将字符串馈送的 IP 地址转换为 IP 地址。

所以,我所做的就是以字符串的形式输入用户的IP。解析它并在 上分割 IP。使用String.split("\\.")

然后,我开始将该字符串数组转换为字节数组,而我现在陷入了困境。

请帮助我摆脱这种情况。任何解决方法或访问此问题的替代方法将不胜感激......

代码如下:-

public static void main(String[] args) {
try{
System.out.println("Enter the IP-Address whose MAC-address you wanna know :-");
Scanner s=new Scanner(System.in);
String ipa=s.nextLine();
String ba[]=ipa.split("\\.");
for(String ap:ba){
System.out.println("Given IP="+ap);
}
byte [] bad=new byte[ba.length];
for(int i=0;i<ba.length;i++){
System.out.println("Ba-"+i+"="+ba[i]);
if(Integer.valueOf(ba[i])>127){
int temp=Integer.valueOf(ba[i]);
//System.out.println("Value of "+i+"---"+temp);
bad[i]=(byte) temp; // this produces error at run-time
}
bad[i]=Byte.valueOf(ba[i]);
System.out.println("Bad-"+i+"="+bad[i]);
}
//byte bad[]={(byte)192,(byte)168,122,1};
InetAddress ia=InetAddress.getByAddress(bad);
............... here is the rest of code and it compiles well.

抛出异常:-

Enter the IP-Address whose MAC-address you wanna know :-
192.168.122.1
Given IP=192
Given IP=168
Given IP=122
Given IP=1
Ba-0=192

Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"192" Radix:10
at java.lang.Byte.parseByte(Byte.java:151)
at java.lang.Byte.valueOf(Byte.java:205)
at java.lang.Byte.valueOf(Byte.java:231)
at NP_7.main(NP_7.java:36)
Java Result: 1

最佳答案

如果您使用InetAddress.getByName(String),您就可以摆脱所有这些麻烦。相反。

您会收到错误,因为字节范围是从 -128 到 127,因此例如 192 超出范围。

您可以通过更改填充 bad 的循环来修复代码:

    for(int i=0;i<ba.length;i++){
System.out.println("Ba-"+i+"="+ba[i]);
bad[i] = (byte) Integer.parseInt(ba[i]);
}

关于java - 从 int 强制转换为 byte 会导致 --- 线程中出现异常 "main"java.lang.NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26949268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com