Why is the array.size '0'? - java

I have the following array:
ArrayList<Integer> myArray = new ArrayList<Integer>();
I also have a variable 'someNum':
int someNum = 12;
My code:
public class Main {
public static void main(String[] args){
int someNum = 12;
ArrayList<Integer> myArray = new ArrayList<Integer>(someNum);
int arraySize = myArray.size();
System.out.println(arraySize);
}
}
Console: '0'
Why is it printing '0'?
I checked the ArrayList documentation is states that array.size(); "Returns the number of elements in this list."
What am I doing wrong?

The size is 0 because you haven't added any members. The argument to the constructor is the initial capacity, not the initial size (or the first element).

The constructor used in
ArrayList<Integer> myArray = new ArrayList<Integer>(someNum);
sets the initial capacity of the ArrayList. This has nothing to do with the number of elements in the ArrayList.

You're calling the ArrayList constructor that accepts as its parameter the initial capacity of the list.
You want instead
myArray = new ArrayList<Integer>();
myArray.add(someNum);
at which point myArray.size() will return 1.

Related

filling values in array

what i want to do is fill the empty aray kyo[] with the add() method but it keeps getting an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
0 at TestPlass.Add(TestPlass.java:30) at
TestPlass.main(TestPlass.java:18)
i'm just new to programming
public static int size = 30;
public static void main (String args[]) {
int kyo[] = {};
Add(kyo);
for(int x:kyo){
System.out.print(x + " ");
}
}
static void Add(int x[]){
for(int g=0; g<=size; g++){
x[g] = g;
}
}
If your kyo array has a fized size, you need to create it with this size.
public static int size = 30;
public static void main(String args[]) {
int kyo[] = new int[size];
add(kyo);
for (int x : kyo) {
System.out.print(x + " ");
}
}
static void add(int x[]) {
for (int g = 0; g < x.length; g++) {
x[g] = g;
}
}
You add function receives int x[] as input, so it should use x.length for the iterator and not your size variable.
I have also edited the name of your Add() method to be add() to respect Java code conventions.
An empty array can never have any content.
Once an array has been created, its size is fixed - you can change the content of the elements, but you can't change how many elements it has. See the Java arrays tutorial for more information.
If you need a dynamically-sized collection, I suggest you use a List<E> implementation, such as ArrayList<E>:
List<Integer> list = new ArrayList<>();
add(list);
for (int x : list) {
System.out.print(x + " ");
}
...
private static void add(List<Integer> list) {
// I assume you want "size" elements, not "size + 1"
for (int g = 0; g < size; g++) {
list.add(g);
}
}
This line:
int kyo[] = {};
creates an array of size zero. Arrays have a fixed size in Java; once an array has been created, its size is fixed. You have to create the array like this:
int[] kyo = new int[30];
This will create an array with 30 elements.
You need to give the size of the array when you create it, like:
int kyo[] = new int[size];
You can find some great info on arrays here:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Arrays do not resize themselves automatically, so the size you initialize it with will be its size forever.
Cheers,
Marcus
Your problem lies here: int kyo[] = {};
{} Creates an array of zero size. Since you are adding 31 elements to the array you need to initialize you array to appropriate size.
For example: int[] kyo = new int[31];

Shuffling elements in an Array (Java)

I need a shuffle method to shuffle elements of an array which holds objects from another class. At the moment I wrote this code to test with integers first, but it seems to not working perfectly. Most of the elements are being duplicated.
Can someone please spot the mistake?
And also come up with a more efficient method for this.
I am not sure if I can use collections.shuffle because I have further use of my shuffled array later.
public static void shuffle()
{
int[] a = new int[52];
int count = 0;
int random = 0;
while (count!=51){
random = (int)(Math.random() * 52);
for (int i=0; i <=count; i++){
if (a[count] != b[random])
result = true;
}
if (result){
a[count] = b[random];
count++;
}
b = Arrays.copyOf(a, a.length);
}
}
First you should not define shuffle() in this way. I would treat b as a parameter and pass it into shuffle() instead of a static field (as your shuffle() is declared as static, your b is also static right? It looks strange to share b between all instances), and result is declared as a local variable.
This part
for (int i=0; i <=count; i++){
if (a[count] != b[random])
result = true;
}
checks whether any one of a[0], a[1] until a[count] is not equal to b[random]. If yes, then assign b[random] to a[count] and increase count by 1. As a[] is not initialized, it is only an array of 0. (a[count] != b[random]) appears to be always true and hence result is true.
Then, for this part,
if (result){
a[count] = b[random];
count++;
}
say for example random=5, then at the first round of the while loop a[0]=b[5], count=1 (due to count++), and b becomes an array of b[5] and a series of 0. (Due to
b = Arrays.copyOf(a, a.length);
all other elements are replaced by 0.)
Edit: Here I provide a simple method, not thoroughly tested, but should work:
public static int[] shuffle(int[] array) {
int[] a = new int[array.length];
//convert int[] to ArrayList<Integer>
ArrayList<Integer> list = new ArrayList<>();
for (int i: array)
list.add(i);
//now shuffle:
for (int i=0; i<array.length; i++) {
int rand = (int)(Math.random()*list.size());
a[i] = list.remove(rand);
}
return a;
}
The array returned is shuffled. Actually I can't say the method "shuffles" the array. It simply creates an empty array, and repeatedly selects an element randomly and put it at the front.
Edit2: This really "shuffles", and this is another approach: does not return a new array. It shuffles the array, 100 times.
public static void shuffle(int[] array) {
for (int i=0; i<100; i++) {
int r1 = (int)(Math.random()*array.length);
int r2 = (int)(Math.random()*array.length);
int tmp = array[r1];
array[r1] = array[r2];
array[r2] = tmp;
}
}
import java.util.Random;
public class Shuffle {
public static void main(String[] args) {
Integer[] a = new Integer[52];
for (Integer i=0;i<a.length;i++) a[i] = i+1;
// Let's shuffle
Random rd = new Random();
for (Integer i=0;i<a.length;i++){
Integer changeBy = rd.nextInt(a.length);
Integer aux=a[i];
a[i]=a[changeBy];
a[changeBy] = aux;
}
// Now show the shuffled array
for (Integer i=0;i < a.length; i++) System.out.print(a[i]+",");
}
}
Hope this small algorithm helps you. As you can see from 2 different runs, it really shuffles your array:
11,1,24,13,28,15,25,48,5,22,12,32,29,42,34,7,33,31,47,18,51,40,8,17,41,20,6,36,21,45,27,52,38,10,30,14,23,19,43,4,50,46,44,3,49,37,35,2,9,26,16,39
3,10,37,26,41,15,28,52,6,24,20,43,33,21,51,32,25,40,50,8,7,5,4,35,13,16,49,17,29,47,12,14,36,39,45,30,2,42,23,38,31,19,27,46,34,11,18,1,22,48,9,44
Why no you HashSet for shuffle?
Elements in java.lang.HashSet are shuffling by their hashcode.
public static void shuffle()
{
int [] b; // you origin array
Set<Integer> temp = new HashSet<Integer>();
for (int i : b) {
temp.add(i);
}
Integer [] a = new Integer[b.length];
a = temp.toArray(a); // new shuffle array
}

Declaration of Array not accepted

I am creating a class that will play the role of a computer player in a virtual game of sticks. However, when I use the constructor method for this class, I lose the array that I have created, even though I had already declared the array in the state attributes. After 20 minutes, I am completely lost.
I am new to Java, and am trying to learn and get better. Any help would really be appreciated.
Below is the redesigned AI class along with the error that Eclipse keeps on submitting.
public class RedesignedAI {
private int[][] largeArray;
private int AIChoiceStick;
private Random random = new Random();
private int CurrentScore[] = new int[51]; //at max, if 100 sticks are initially chosen, then each player takes at max 50 sticks,
private int h = 0; //^so why not have one more in case
public RedesignedAI(int NumberSticks) //this is a constructor method and creates the arrays that contains a
{
largeArray[][] = new int[NumberSticks][3];
int i = 0;
while(i < NumberSticks)
{
largeArray[i][0] = 1; //ADD THIS
largeArray[i][1] = 1;
largeArray[i][2] = 1;
i++;
}
}
The error: largeArray cannot be resolved to a type.
You initialized the largeArraythe wrong way. Use:
largeArray = new int[NumberSticks][3];
That new allocate a 2D array, so types are coherent both sides of the =.
If you want to allocate chunk by chunk then you should use [] syntax:
largeArray = new int[NumberSticks][]; // array of NumberSticks entries to array of int (not yet determined)
for (int i=0; i<NumberSticks; i++) {
largeArray[i] = new int[3]; // i-th entry of array largeArray is a new array of 3 ints
}
largeArray is a reference to array of reference to array of ints. largeArray[i] is a reference to array of ints. largeArray[i][j]is an int.
Try this
private int[][] largeArray = null;
Initially initialize with null.
then in constructor
largeArray[][] = new int[3][3];
Since value is dynamic and you are changing it anyhow
You have to initialize the array on the top:
private int[][] largeArray = new int[x][y];
An array always has a fixed length. Only a list can variate the length.
Change this:
largeArray[][] = new int[NumberSticks][3];
into this:
largeArray = new int[NumberSticks][3];
Wrong Code:
largeArray[][] = new int[NumberSticks][3];
Instead use:
largeArray = new int[NumberSticks][3];
You don't need the [][] in the largeArray code of the constructor. This will do:
largeArray = new int[NumberSticks][3];
You may find it easier to use ArrayList instead. Maybe something like this:
private List<List<Integer>> largeArray;
...
public RedesignedAI(int NumberSticks) {
largeArray = new ArrayList<>();
int i = 0;
while(i < NumberSticks) {
List<Integer> innerArray = new ArrayList<>();
innerArray.add(1);
innerArray.add(1);
innerArray.add(1);
largeArray.add(innerArray);
i++;
}
}

Returning an Array of Integers

I am trying to make a method in which it will take an array of integers as a parameter, creates a new array that is the same size, copies the elements from the first array into the new array, and then returns a reference to the new array.
Right now, my code is as follows:
class CopyingAnArray {
int[] cloneArray(int[] arr) {
size = newarray.length;
int[] newarray = new int[size];
int[] copyarray = newarray;
return copyarray;
}
public static void main(String argv[]) {
ArrayTester converter = new ArrayTester();
int[] newarray = {2,5,6,7};
System.out.println(converter.cloneArray(newarray));
}
}
Here is an explanation of what I think I am doing. I am taking the size of an array and putting it an array:
size = newarray.length;
int[] newarray = new int[size];
Then I am copying the array into a new array named copyarray. Then, I return copyarray.
int[] newarray = new int[size];
int[] copyarray = newarray;
return copyarray;
Any suggestions or advice on what I did wrong/solve the code?
so I tried doing this instead:
So, I will do something like this:
int[] cloneArray(int[] arr) {
int size=arr.length;
int[] arr=new int[size];
int[] arr=newarray;
for (int i=0; i<arr.length; i++) {
arr[i]=newarray[i];
return newarray[i];
}
}
I am still getting errors though.
Multiple things. You need to declare size as an int. The major things: you never use the parameter passed to the method, arr. You use size = newarray.length when newarray doesn't exist yet. You try to make copyarray = new array, which doesn't make much sense. In addition, when setting two arrays equal to each other, you aren't really copying, you are only copying the reference to the array in memory. In order to copy, make a new array with the length of the parameter, then iterate over it with a for loop and copy each value into the new array, then return the new array. You can also always use Arrays.copyOf(array,array.length);

how to fix with array OutOfBoundsException?

I'm working on a project for school where we have to spin a cube a number of times and find the longest run of the numbers that are received from the cube. I am almost finished with the code, and it complies, but whenever I run it I get the same error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at number_cube.number_cube.cubeToss(number_cube.java:20)
at number_cube.number_cube.main(number_cube.java:10)
Can anybody help me with this?
Here is my code:
public class number_cube {
public static int ans;
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
System.out.println("How many times would you like to toss the cube?");
ans = scan.nextInt();
cubeToss();
getLongestRun();
System.out.println();
}
public static int arr[] = new int[ans];
public static int[] cubeToss(){
for(int i = 0; i < ans; i++){
int randnum = (int) (1 + Math.random() * (6-1));
arr[i] = randnum;
}
return arr;
}
public static void getLongestRun(){
int longest = 0;
int length = 1;
for(int i = 1; i < ans; i++)
if(arr[i] == arr[i-1]){
length++;
}
else{
length = 1;
}
if(length > longest){
longest = length;
}
System.out.println("The longest run is " + longest + ".");
}
}
You used the variable ans as the length of your arr array, but when the array was created, ans didn't have a value (Java initialized it to 0), so the arr array has length 0. The main method isn't called until the class is initialized; all static variables are initialized before the main method is called.
Don't create the array until you have a valid length:
ans = scan.nextInt();
arr = new int[ans]; // Add this line.
cubeToss();
You need to initialize the array after you got the value for ans. Currently you are initialize the Array with ans = 0 at the startup for the program (where ans is 0).
A correct solution may be:
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
System.out.println("How many times would you like to toss the cube?");
arr[] = new int[scan.nextInt()];
public static int arr[] = new int[ans];
From the jls-12.4: when The JVM is still trying to execute the method main of class number_cube, the invocation is permitted only if the class has been initialized. However, Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class.
That is why, static fields declared in class context always gets instantiated first.
For your class which are: int[] arr and int ans. static variable ans initialized to the value 0 which is default value of integer. Hence, Instantiating the static array arr has the length 0 and being empty. When you are trying to access it in the cubeToss() function using a loop, an AIBE 0 is being thrown as the array has length 0(or, the array is empty).
So, after reading the ans in the main method in the main method using ans = scan.nextInt();, try creating the array in the main method: arr = new int[ans]
public static int[] arr;
and then initialize only after getting ans from System.in

Categories