Reputation: 41
I am a beginner at java and I con't understand why this isn't working. I am trying to write a program that converts a base 10 number to a binary one, but I'm having an issue with an ArrayList. I can't use the add method of the ArrayList:
import java.util.ArrayList;
import java.util.Scanner;
public class DecimalToBinary {
public static void main (String[] args){
Scanner reader = new Scanner (System.in);
System.out.println("This program converts a decimal number to binary.");
int decimal;
ArrayList<int[]> binary = new ArrayList<int[]>();
//Gets decimal number
System.out.print("Enter base 10 number: ");
decimal = reader.nextInt();
//Adds 1 to binary and then adds the remainders of decimal/2 after that until decimal is 1
binary.add(1, null);
while (decimal != 1){
binary.add(1, decimal%2);//This is where I get the error
decimal = decimal/2;
}//Ends While loop
}//Ends main
}//Ends DecimalToBinary class
Upvotes: 1
Views: 3347
Reputation: 55
On this line:
ArrayList<int[]> binary = new ArrayList<int[]>();
You are declaring that the ArrayList will contain only arrays of type int. In other words, every object stored in 'binary' will be an array of int's.
So, when you write:
binary.add(1, decimal % 2);
You are trying to add 'decimal % 2' to the position 1 of binary. Because decimal % 2 is an int, and not an array of int's, you get a compiler error.
Change the declaration of binary to:
ArrayList<Integer> binary = new ArrayList<Integer>();
Upvotes: 1
Reputation: 9813
ArrayList <Integer> binary = new ArrayList <Integer>();
binary.add(3);
Upvotes: 0