代码编译得很好,但会出现运行时错误,例如
Exception in thread "main" BitBin.IndexOutOfRangeException: out of range
at BitBin.decmalToBinary.birBin(decmalToBinary.java:52)
at BitBin.decmalToBinary.main(decmalToBinary.java:42)
我不太确定问题是什么,因为我在代码中抛出了如下异常:对不起,当我输入除数字之外的任何内容时,它对我有异常,你能帮我吗?例如我输入字符而不是数字
package BitBin;
import java.util.Scanner;
public class decimalToBinary {
static int decToBin (int n) {
int term = 0;
while (n != 0) {
term ++;
n /= 2;
}
return term;
}
static String ArrayBinToStr (int[] Array) {
String ret = "";
for (int i = Array.length-1; i >= 0; i--)
ret += Integer.toString(Array[i]);
return ret;
}
public static void main (String[] args) {
Scanner sc=new Scanner (System.in);
System.out.print ("Enter number : ");
int num = sc.nextInt();
int[] bin = new int[decToBin (num)];
int dup = num, el = -1;
while (dup != 0) {
int rem = dup % 2;
bin [++el] = rem;
dup /= 2;
}
String d2b = binBit(bin);
System.out.println("Binary of " + num + " is: " + d2b);
}
static String binBit(int []d2b) throws IndexOutOfRangeException{
Scanner sc=new Scanner (System.in);
System.out.print ("Enter bit: ");
int bit = sc.nextInt();
if(bit>d2b.length-1 || bit<0)
throw new IndexOutOfRangeException("out of range");
String rit="";
int i=bit;
if(d2b[i]== 0 )
System.out.println("bite " +i+ " om 0 ast.");
else
System.out.println("bite " +i+ " om 1 ast.");
for (i = d2b.length-1; i >= 0; i--){
rit+=Integer.toBinaryString(d2b[i]);
}
return rit;
}
}
}
SAMPLE INPUT FILE
Enter number:
Enter bit: