Hey,
hab ich will ein Programm schreiben, dass dezimal Zahlen in binäre umwandelt; hier der code:
public class While {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int [] bin = new int[10];
int x=0;
int z=1;
int erg =Integer.parseInt(args[0]);
while( erg >= 1){
System.out.println(erg);
if(erg==0){
bin[x]=0;
} else if (erg%2==0){
bin[x]=0;
erg = erg/2;
x++;
}
}
int a = Array.getLength(bin);
System.out.println(a); // Meiner Meinung nach müsste er bei Eingabe 20 doch 5 ausgeben?
while ( Array.getLength(bin) >= 0){
System.out.print(bin[Array.getLength(bin)-z]);
z = z+1;
}
}
}
Wenn ich das nun ausführe kommt:
20
10
5
2
1
10
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at pkgwhile.While.main(While.java:42)
0000010100Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Ich verstehe nicht warum er mir soviele 0er ins Array reinschreibt ?
hab ich will ein Programm schreiben, dass dezimal Zahlen in binäre umwandelt; hier der code:
public class While {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int [] bin = new int[10];
int x=0;
int z=1;
int erg =Integer.parseInt(args[0]);
while( erg >= 1){
System.out.println(erg);
if(erg==0){
bin[x]=0;
} else if (erg%2==0){
bin[x]=0;
erg = erg/2;
x++;
}
}
int a = Array.getLength(bin);
System.out.println(a); // Meiner Meinung nach müsste er bei Eingabe 20 doch 5 ausgeben?
while ( Array.getLength(bin) >= 0){
System.out.print(bin[Array.getLength(bin)-z]);
z = z+1;
}
}
}
Wenn ich das nun ausführe kommt:
20
10
5
2
1
10
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at pkgwhile.While.main(While.java:42)
0000010100Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Ich verstehe nicht warum er mir soviele 0er ins Array reinschreibt ?