【发布时间】:2014-11-15 18:33:27
【问题描述】:
我正在编写一个程序,利用InetAddress.getByAddress(byte[] addr) 方法将字符串馈送的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
【问题讨论】:
-
我想知道谁否决了这个问题,因为我没有得到我需要的确切解决方案!
标签: java network-programming bytearray arrays numberformatexception