Declaration of Array not accepted - java

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++;
}
}

Related

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);

indexOf int array elements

I have this code is to find the indexOf 3 elements in array, so I used java.util.. etc, but it gives me that there I mistake the result is -1, how to avoid this wrong answer, and is there another way to write this code
int array [] = {1,0,1,0,0,1,1,0,1,1};
for(int counter = 0 ; counter < 3; counter++)
System.out.printf("%5d%8d\n",java.util.Arrays.asList(array).
indexOf(array[randomNumbers.nextInt(10)]),array[randomNumbers.nextInt(10)]);
I'm not sure if I've got the answer, but try breaking up your code into readable lines. And your original array should be Integer[] instead of int[].
Note that Arrays.asList(int[]) creates a List<int[]>.
Random randomNumbers = new Random();
Integer array [] = {1,0,1,0,0,1,1,0,1,1};
for(int counter = 0 ; counter < 3; counter++)
{
int randomItemFromArray = array[randomNumbers.nextInt(10)];
List<Integer> listOfInts = Arrays.asList(array);
int indexOfRandomItem = listOfInts.indexOf(randomItemFromArray);
System.out.printf("%5d%8d\n", indexOfRandomItem , randomItemFromArray);
}
This might help.
You have to use wrapper class of "int"
SecureRandom randomNumbers = new SecureRandom();
Integer array[] = { 1, 0, 1, 0, 0, 1, 1, 0, 1, 1 };
for (int counter = 0; counter < 3; counter++)
System.out.printf("%5d%8d\n", java.util.Arrays.asList(array).indexOf(array[randomNumbers.nextInt(10)]), array[randomNumbers.nextInt(10)]);
(Edit - 02.03.2014)
Hi, my first answer was wrong, check the new one:
SecureRandom randomNumbers = new SecureRandom();
/**
* I don't know why but when you create an array with only primitive
* contained "unnamed block" like "Integer array[] = {1,0,1}". JVM
* associate same referance variables with same values like "Integer
* array[] = {#34, #554, #34}". That is why i use "new Integer"
* constractor for each integer as follows:
*/
Integer array[] = new Integer[] { new Integer(1), new Integer(0),
new Integer(1), new Integer(0), new Integer(0), new Integer(1),
new Integer(1), new Integer(0), new Integer(1), new Integer(1) };
int ran, i;
for (int counter = 0; counter < 3; counter++) {
ran = randomNumbers.nextInt(10);
i = 0;
/**
* "List.indexOf" method uses "object1.equals(object2)" method, this
* method compares "values" of wrapper classes, but in your case
* we have to compare referances, so with nested "for" loops we
* check that:
*/
for (Integer integer : array) {
if (integer == array[ran]) { // "==" operator checks referances is same
System.out.printf("%5d%8d\n", i, ran);
break;
}
i++;
}
}
Problem is with the int[] array itself because when you use any primitive array and convert it to a List using Arrays.asList() it will return a List<int[]> not List<Integer> hence the issue occurring with your code. to resolve create array of Integer (Wrapper class)
Integer[] array = {1,0,1,0,0,1,1,0,1,1};
Why your code fails:
This is relevant:
Arrays.asList() not working as it should?
You call Arrays.asList on an int[]. This does not produce the expected result because Arrays.asList is made to work with an array of Objects, not primitives. The result is a list of one element, that element is your int[] array (because an array of primitives is an Object, like any other array).
The solutions:
You already know your index. You're setting it. No need to look it up. Save it in a variable. I love short code, but sometimes short code is worse and runs slower than slightly longer code. NBD if you didn't fit the entire program on one line. -OR-
If you still think you need an index lookup, use an array of integer objects (Integer[]).

Why is the array.size '0'?

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.

Fluctuating array sizes

When I learned java, I was told that once created, the size of an array was fixed and couldn't be changed. Recently I've been using arrays a lot and have noticed that code similar to the following doesn't generate errors:
public class Test {
private static String[][] smallArray = new String[4][4];
private static String[][] biggerArray = new String[21][21];
private static String[][] assignedLater;
public static void main(String args[]){
for(int i = 0; i < smallArray.length; i++){
for(int j = 0; j < smallArray[0].length; j++){
smallArray[i][j] = i + j + "";
}
}
for(int i = 0; i < biggerArray.length; i++){
for(int j = 0; j < biggerArray[0].length; j++){
biggerArray[i][j] = i + j + "";
}
}
assignedLater = smallArray;
//last element of last row
System.out.println(assignedLater[3][3]) //returns 6
assignedLater = biggerArray;
//new last element of new last row
System.out.println(assignedLater[20][20]) //returns 40
}
}
After playing around with this for a bit, I ended up testing the following:
public class Test {
private static String[][] smallArray = new String[2][4];
private static String[][] biggerArray = new String[2][21];
private static String[][] errorArray = new String[3][21];
private static String[][] assignedLater = new String[2][0];
public static void main(String args[]){
//fill arrays as in previous example
assignedLater = smallArray;
//last element of last row
System.out.println(assignedLater[1][3]) //returns 6
assignedLater = biggerArray;
//new last element of new last row
System.out.println(assignedLater[1][20]) //returns 21
assignedLater = errorArray; //no error
System.out.println(assignedLater[2][20]); // returns 22
}
}
What's going on here?
Edit
Thanks for the responses, I am hereby enlightened as to why the impossible isn't actually happening.
You are not changing the size of arrays. You are just changing the reference to point to a different array in memory.
The arrays do not change size at all, what you are doing is making the varibles change reference, they will simply change which array they point to without those arrays changing size.
As Juned said you're just changing the reference so you don't need such a complicated example to demonstrate. Even this will suffice:
int[] smallArr = new int[5];
int[] bigArr = new int[5000];
smallArr = bigArr;
System.out.println(smallArr.length); // -> prints 5000...
but we still haven't changed the length of a static array, just changed the location to which smallArr refers to be where bigArr refers.
In your second block, when you have this line, you gave 'assignedLater' some dimensions:
private static String[][] assignedLater = new String[2][0];
But then, in your main function, you pointed it to different arrays, so the old dimensions no longer matter:
assignedLater = smallArray;
After this, any call to assignedLater indices will point to smallArray indices. (until you reassign it again later). And so on.

Java array issue

How would I go about creating an array of say 5 items and then after create an array for each item?. I know how to create an array of 5 items but the problem I have is creating an array for each one after. Im assuming I would need 5 arrays since there's 5 items.
int gas = 0;
int food = 0;
int clothes = 0;
int entertainment = 0;
int electricity = 0;
int[] budget = new int[4];
budget[0] = gas;
budget[1] = food;
budget[2] = clothes;
budget[3] = entertainment;
budget[4] = electricity;
thanks in advance
Instead of creating a 2-dimensional array holding types of amounts that are logically grouped together (I assume per month) it would be better to define a data-holder class so that you can access the amounts using their name instead of an error-prone index.
For example (minus the getters and setters):
public class Budget {
public int gas = 0;
public int food = 0;
public int clothes = 0;
public int entertainment = 0;
public int electricity = 0;
};
// ....
Budget[] months = new Budget[12];
budget[0].gas = gasCosts;
budget[0].food = foodCosts;
// etc
Are you saying you want to create a 2D array? Each element in the budget array is another array?
You'd use a loop.
int[] budget = new int[5]; //There are 5 elements to be stored in budget, not 4
for (int y = 0; y < 5; y++) {
budget[y] = new int[5];
}
Maybe you need a matrix.
int[][] budget = new int[4][4];
In the first index you keep the budget and in the second index the five (in the case above) budget items.
When you have a matrix [x][y] you have x+1 arrays each of wich with y+1 elements.
There are 5 elements in the array.
int[] budget = new int[5];
budget[0] = gas;
budget[1] = food;
budget[2] = clothes;
budget[3] = entertainment;
budget[4] = electricity;
You need 2-dimensional array, which is basically an array of array. The 2D array is declared by 2 pairs of []. In the following example, each budget have 10 details.
String[][] detail = new String[budget.length][10];
If I'm understanding you correctly, you want a 2d array that would be something like ...
int gas = 0;
int food = 1;
int clothes = 2;
int entertainment = 3;
int electricity = 4;
int maxEntries = 10;
int[][] myArray = new int[5][maxEntries];
This could be accessed via:
myArray[gas][entryNumber] = 6;
int value = myArray[gas][entryNumber];
But how inflexible this is? You have to know in advance how many entries there will be for each "category" or have code that checks a given array length when you're adding an item, creating an new array when you need a larger one (and copying the old data into it).
What you probably want at the very least is a ArrayList of ArrayLists:
ArrayList<ArrayList<Integer>> my2dArrayList =
new ArrayList<ArrayList<Integer>>();
...
my2dArrayList.get(gas).add(someValue);
int myValue = my2dArrayList.get(gas).get(index);
Or a HashMap of ArrayLists you could access via the names of your categories:
HashMap<String, ArrayList<Integer>> myMap =
new HashMap<String, ArrayList<Integer>>();
...
myMap.get("gas").add(someValue);
int myValue = myMap.get("gas").get(index);

Categories