I've been trying to write a small and simple program that converts dec numbers to bin.The idea is that when the user enters a positive integer a for- cycle have to go through all the rounds of deviding the number /2 but it also have to get the tail (idk the math term really the actuall bin numbers) and write them in an array, thats the part Im having trouble with.I have predefined the array size of 30 (cant find a way to make a working array without specifying it's length) my idea was that then I could make a reversed array with length = index(i from the first for cycle) from the previous array with another for cycle etc. but when I tested the first array all I get is empty brackets printed: [] or nothing at all, eclipse doesnt find any errors in the code and I cant figure out whats wrong.I could use some help.Anyways here's the code:
public static void decToBin(){
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer:");
n = in.nextInt();
in.close();
if (n <= 0) {System.out.println("ERROR:n<=0");return;}
else if (n > 0){
int[] ostataci = new int[30];
for (int i = 0;n <= 0;i++){
ostataci[i] = n % 2;
n = n / 2;
// System.out.printf("%d %n", ostataci[i]); - even this one doesnt print at all
}
// System.out.println(Arrays.toString(ostataci)); - nor this one
}
}
Thanks for the replies Ive learnt a few new things.But since Im a newbie I wanted to do it with the metod I described thx for pointing me the error in the for cycle, that was my biggest problem, anyway heres the last code I wrote( working correctly) thats what I was trying to do from the beggining.
public static void decToBin2(){
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer:");
n = in.nextInt();
in.close();
int i = 0;
int[] ostataci = new int[32];
if (n <= 0) {System.out.println("ERROR:n<=0");return;}
else if (n > 0){
while (n > 0){
i++;
ostataci[i] = n % 2;
n = n / 2;
}
}
int reverse = i;
int[] reversed = new int[reverse];
for (int i2 = 0;i2 != reverse;i--,i2++){
reversed[i2] = ostataci[i];
System.out.print(reversed[i2]);
}
}