Initializing a three dimensional array of arraylist in Java - java

I have a multidimentional array, as:
private static ArrayList [] [] pVTable = new ArrayList [35] [12];
My first try to initialize it was:
for (ArrayList[] x : pVTable) {
for (ArrayList y : x) {
y = new ArrayList<TableValue>();
}
}
which didn't work.
I ended up doing it more manually, as in:
for ( int i = 0; i < pVTable.length; i++) {
for ( int j = 0; j < pVTable[0].length; j++) {
pVTable [i] [j] = new ArrayList<TableValue>();
}
}
which works fine.
Although I have a solution, I was wondering why the first (more elegant) piece of code doesn't do the same job?

In the first snippet, if we strip away the syntactic sugar of the foreach operator (:), the code translates to:
for (int xIndex = 0; xIndex < pVTable.length; xIndex++) {
ArrayList[] x = pVTable[xIndex];
for (int yIndex = 0; yIndex < x.length; yIndex++) {
ArrayList y = x[yIndex];
y = new ArrayList<TableValue>();
}
}
As you can see, nothing is ever assigned to the actual array – only to the temporary y variable.

In the first example your code although modifies y does not change x.

You are mixing ArrayList (part of collections api) with Arrays, which is rather confusing (for me anyway)
I would suggest something like this instead :
List<Point> myShape = new ArrayList<Point>;
Where point contains two ints representing X and Y.

The scope of the first is incorrect. y is just a placeholder variable. Changing that doesn't change the underlying object, just the object that y refers to. You can see the same problem in the following code snippet:
public static int x = 2;
public static void foo(int y) {
y = 3;//does nothing outside of foo
}
public static void main(String[] args) {
System.out.println(x);//prints 2
foo(x);
System.out.println(x);//prints 2, x hasn't changed.
}

Related

Rewriting array form Object[] to float[] in Java

I have to get an float[] array from an TockaXY[] array.
Example of TockaXY[] with 4 elements:
[60.039005,86.44917][96.53153,41.086178][19.988914,31.67395][96.84925,41.90731]
but I need an float[]. Tried:
for (int i = 0; i < objectArray.length; i++)
floatArray[i] = (Float)objectArray[i];
But I get error cannot Cast.
Any Ideas?
If i understood it right, you have an array within an array.
if you want to keep it this way than you have to create another array within an array
so;
float floatArray[][]; //declare a 2D array
floatArray = new float[4][2]; //make it's length same as yours
for (int i = 0; i < objectArray.length; i++){
for(int j =0; j<objectArray[i].length; j++){
//parse each value as float, and assign it to your new array
floatArray[i][j] = Float.parseFloat(objectArray[i][j]);
}
}
First of all your given element is not array, its array of array.
You can try this to convert Object[][] to Float[][].
Object[][] objectArray = { { 60.039005, 86.44917 }, { 96.53153, 41.086178 }, { 19.988914, 31.67 },
{ 96.84925, 41.90731 } };
Float[][] floatArray = new Float[objectArray.length][2];
for (int i = 0; i < objectArray.length; i++) {
floatArray[i][0] = ((Double) objectArray[i][0]).floatValue();
floatArray[i][1] = ((Double) objectArray[i][0]).floatValue();
}
System.out.println(floatArray);
Assuming TockaXY is something like
public sclass TockaXY {
private float x;
private float y;
//Constructors, getters, setters etc.
#Override
public String toString() {
return "["+ x + ", " + y + "]";
}
}
and you want a float[] containing the values of x and y from each element of a TockaXY[], the size of the float[] must be 2 * size of TockaXY[].
float [] floatArray = new float[objectArray.length * 2];
for (int i = 0, j=0; i < objectArray.length; i++) {
floatArray[j++] = objectArray[i].getX();
floatArray[j++] = objectArray[i].getY();
}
This: (SomeType) someExpr; is called a cast operation. Unfortunately, there are 3 completely different things that java can do, that all look exactly like this. A real guns and grandmas situation!
Casts can convert things, or can assert generics in types, or can coerce types itself. The latter two, at runtime, do nothing (maybe throw ClassCastException), it's just ways to tell the compiler you know what you are doing; to treat things as different types.
The ONLY one that converts anything is the 'type conversion' mode, and that one only kicks in if both the type in the parentheses and the expression you're applying it on are primitive (auto-unboxing may kick in, but it ends there).
Float is not primitive (float is primitive), so you're not doing a type conversion here, but your question makes it sound like you think you are.
Okay, and.. how do I fix my code?
It looks like TockaXY is a class that looks something like:
class TockaXY {
public float x, y;
}
From your question it is unclear what you want here. Do you want all 8 floats in an 8-sized float array? Do you only want the 'x' elements? Only the 'y' elements?
A TockaXY is not a float (it's a coordinate), so this is not easy, you'd have to program that. For example:
TockaXY[] in = ...;
float[] fs = new float[in * 2];
for (int i = 0; i < in.length; i++) {
fs[i * 2] = in[i].x;
fs[(i * 2) + 1] = in[i].y;
}

Java is giving me different results for the same process

what i mainly want to know is :
in the line public static void val(int[] x) what does the (int[] x) do?
Also: why am i getting the final added up values when i ask
for(int y:i){
System.out.println(y);
}
but not for:
int y=2+i2;
System.out.println(y);
why isnt the vale() method not converting the "i2" value to "x" immediately and then continuing the compilation by using the "x" value for subsequent 'i2" calculations....sorry if my question is vague....i just dont know how else to put it....thanks
complete code:
public static void main(String[] args) {
int[] i = { 25, 22 };
int i2 = 41;
val(i);
for (int y : i) {
System.out.println(y);
}
vale(i2);
int y = 2 + i2;
System.out.println(y);
}
public static void val(int[] x) {
for (int c = 0; c < x.length; c++) {
x[c] *= 2;
}
}
public static void vale(int x) {
x += 23;
}
Java always passes arguments by value, never by reference (not only primitive types, reference types as well). This is why your vale(int x) method doesn't work.
Have a look at this article, it explains everything: http://www.javaworld.com/article/2077424/learn-java/does-java-pass-by-reference-or-pass-by-value.html
I think you need to read about pass by value and reference in Java. Regarding your questions, both val(i) & vale(i2) are technically pass by value. Since array is an object type, its reference is passed to the method in case of val(i) and hence you could see the modifications when you print the reference. However, vale(i2) takes a primitive integer type as parameter and thus the modifications within the method doesn't affect the original value. To understand this better you can modify your val(int[] x) method as follows:
public static void val(int[] x) {
x = new int[] {35, 57};
for (int c = 0; c < x.length; c++) {
x[c] *= 2;
}
}
I just added x = new int[] {35, 57}; which would make the value of x point to a different reference and not affect the original value. Hope this clarifies!
Your method val(int[] x) accomplishes absolutely nothing in this code. It returns void(nothing) to the main() function and the operations you preform inside val() with your array x are done on a copy of x...
possible fix:
public static int[] val(int[] x){
int[] newarr = new int[x.length];
for (int c=0; c<x.length;c++){
newarr[c] = x[c]*2;
}
return newarr;
}
in main:
int[] i={25,22};
i = val(i); // creates an array with every element doubled and assigns it to i
same story with vale() !

Find element position array in java

I need to write some methods for a game in java and one of them is int[] findStone. The method returns an array, which gives the coordinate of the element that I am searching.
The field looks like this and is defined like this: private static int[][] gamefield = new int[8][6];
So if I use the method: findStone(3)[0], it should return 0 for the x coordinate and for findStone(3)1, 2. This is the code that I wrote.
private static int[] findStone(int stone) {
int[] position = new int[2];
for(int x = 0; x < 8; x++ ){
for(int y = 0; y < 6; y++ ) {
int a = gamefield[x][y];
int i = x;
int j = y;
if(a == stone) {
position[0] = i;
position[1] = j;
}
break;
}
}
return position;
}
The problem is: The method only returns the x-coordinates for the first row corectly, for the other elements it shows me 0. Could someone explain me what I did wrong and what I should change? Please, only simple explanation. I am only at the beginning and I don't have experience in java.
Thank you :)
You probably intended to put your break clause inside the if block. The way you have it now, the break keyword has no effect. It just breaks the inner loop (with y variable), but since this block of code ends here anyway, it simply does nothing.
You're searching for a single point on your map, so when you find the stone position, you can immediately return it, as there's nothing more to do.
Moreover, you don't need additional variables, a, i and j. Using them is not wrong, but code looks clearer and is more concise without them. Have a look at this code:
private static int[] findStone(int stone) {
int[] position = new int[2];
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 6; y++) {
if (gamefield[x][y] == stone) {
position[0] = x;
position[1] = y;
return position;
}
}
}
return null; // if there's no given stone
}

Accessing a returned list in the main method

So basically I have a static class that returns a newly made list and what I need to do is print each element of said list by using it in the main method. I get the error that cant solve blablabla to a variable which I guess means that the list I am trying to use is not usable yet. Thought it might be a good idea to add the last lines here as well for a visual.
The error code given is "b cannot be resolved to a variable".
public class A5P5 {
public static int[] teine(int arv, int alum, int ylem) {
int [] b = new int[arv];
for (int i = 0; i < arv; i++) {
double k = Math.random() * (ylem-alum) + alum;
int l = (int)k;
b[i] = l;
}
return b;
}
public static void main(String[] args) {
int [] a = new int[10];
for (int i = 0; i < 10; i++) {
double x = Math.random() * (110-50) + 50;
int y = (int)x;
a[i] = y;
}
for (int elem: a) {
System.out.println(elem);
}
System.out.println("----------------------------------------------------");
teine(20, 20, 40);
for (int elem: b) {
System.out.println(elem);
}
}
}
Try:
...<delete teine(20, 20, 40);>...
for (int elem: teine(20, 20, 40)) {...
you have to assign the value returned from the method above so an alternative would be:
int[] b = teine(20, 20, 40);
for (int elem: b) {...
you cannot acces b because it is a local var in your teine method, so that won't work in main:
teine(20, 20, 40);
for (int elem: b) {
System.out.println(elem);
}
but since teine returns your b anyway you can just do this:
for (int elem: teine(20, 20, 40)) {
System.out.println(elem);
}
My bet is that the compilation error is about this line:
for (int elem: b) {
Hints:
Which b do you think that refers to?
The b declared in your tiene method is out of scope at that point. Specifically, the variable b goes out of scope when the call to tiene finishes.
To start that isn't a List it's an Array. They are quite different.
Now about your issue. You are making a new int array in your main but not populating it with anything so (according to the specs) each element has a value of 0.
You need to actually call and assign your array. int[] a = teine(arv, alum, ylem) would be a good place to start moving forward with your program.
I would also agree with #Brian Roach that you may need to brush up on your basics. Also try using more descriptive names for your variables. It will help both people reading your code and yourself when you come back to the code down the line and need to debug or modify it.

Understanding constructors and "this"

I'm learning constructors and I understand them for the most part, but I must not understand it enough. I also don't understand this fully. But this code below is supposed to use these constructors:
default constructor, which will be used to fill the matrix with random doubles
constructor which takes a File object, which points to a file
containing a matrix,
constructor which takes a string, which contains the name of the file
constructor which takes a value of type Matrix, and makes a copy of it
constructor which takes a 2D array, and copies its values
And some more, along with a static multiply method. I am supposed to use the commands that are found in main. But I don't quite understand how using a String as the only parameter will do the constructor it's told to, and also the other ones like the default constructor that fills the array with random doubles. I think I should be using this more in my code, but I'm not quite sure.
I mainly just need to be able to set a matrix, fill m1 matrix with random doubles, do it again with m2 matrix, and then use the static multiply method to multiply them, then output the resulting matrix. Thank you.
(Just a heads up, I'm using a 3 by 3 matrix, originally I was supposed to set the size of the matrix to the one found in the text file, but I can also specify the size I want, which I am. And sorry for the messy code. It got all jumbled up while I was trying to figure this stuff out, and I'm afraid of altering it further.)
public class Matrix {
double A[][] = new double[3][3]
// Matrix file name
public Matrix(String name) {
this(new File(name));
}
// Matrix random fill
public Matrix() {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
this.A[i][j] = (min + Math.random() * (max - min));
}
// Matrix copy
public Matrix(double[][] A) {
private double[][] arrcopy = new double[3][3];
private double[][] array = new double[3][3];
array = A;
for(int i = 0; i < 3; ++i){
for(int j = 0; j < array[i].length; ++j) {
arrcopy[i][j] = array[i][j];
}
}
}
// Set array from text file
public Matrix(File a) {
File f = a;
Scanner inputStreamOne = null;
try{
inputStreamOne = new Scanner(f);
}
catch(FileNotFoundException e){
System.out.printf("Error\n");
}
double arrayOne[][] = new double[3][3];
while(inputStreamOne.hasNextInt()) {
for(int i = 0; i < 3; ++i){
for(int j = 0; j < arrayOne[i].length; ++j){
arrayOne[i][j] = inputStreamOne.nextInt();
}
}
inputStreamOne.close();
}
}
// Gets array in file from string name
public Matrix(String a) {
String inputOne = a;
Scanner inputStreamOne = null;
try{
inputStreamOne = new Scanner(new File(inputOne));
}
catch(FileNotFoundException e){
System.out.printf("Error\n");
}
while(inputStreamOne.hasNextInt()){
for(int i = 0; i < size; ++i){
for(int j = 0; j < arrayOne[i].length; ++j){
arrayOne[i][j] = inputStreamOne.nextInt();
}
}
inputStreamOne.close();
}
}
public static multiply
public static void main(String args[]) {
Matrix m = new Matrix("matrix1.txt");
Matrix m2 = new Matrix("matrix2.txt");
Matrix r = Matrix.multiply(m, m2);
r.output(...);
}
}
Within a constructor or a method this refers to the current object. Within a constructor, if you just use a bare this ( which is to say this without a .method after it ) then it refers to another constructor of the same object that has a different type signature.
Constructors, like any function in Java, can be overloaded. Which is to say, because of Java's type system you can have multiple functions that are of the same name so long as they have different type signatures.
class Foo {
public Foo ( String arg ) {
this(arg, "World");
}
public Foo ( String arg1, String arg2 ) {
// do stuff with arg1 and arg2
}
}
In the above example, one constructor takes a single string and the other takes two. Java won't magically know what to do with the data passed into different constructors. What you have to do is write code in each method so that the resulting object is the same. ( Well technically you don't have to do that, but it's good form ( usually overloaded constructors are for setting default values or for the ease of use of other programmers ))
The this keyword refers to the current object in a constructor or a method, i.e. the object whose constructor or method is being called. Within a constructor, you can also use this to call another constructor in the class.
Refer to http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html for a clear explanation from Java Tutorials.

Categories