Confused with Array in Java - arrays

Could someone please answer why the output of this code is 225? Why not 222 since you are changing a?
When you look at code no.2 a when a is passed to test(), it completely changed. My question is why is that 'a' in number 1 did not change when passed to test() while 'a' in number 2 changed?
I'm a beginner at Java.
1.
public class Array1
{
static void test(int[] a)
{
int[] b = new int[2];
a = b;
System.out.print(b.length);
System.out.print(a.length);
}
public static void main(String[] args)
{
int[] a = new int[5];
test(a);
System.out.print(a.length);
}
}
2.
public class Array2
{
static void test(int[] a) {
int[] b = new int[2];
for(int i =0; i< a.length; i++)
{
a[i]=1;
}
}
public static void main(String[] args)
{
int[] a = new int[5];
test(a);
for(int i =0; i< a.length; i++)
{
System.out.print(a[i]);
}
}

Let's see what happens step by step in case 1
main: int[] a = new int[5]; : declares a ref variable in main pointing to a array of 5 ints
main: test(a); : calls test with a reference to the original array
test: static void test(int[] a) { : declares a ref variable a to hold a ref to the caller array => a in test is another reference to the original array
test: int[] b = new int[2]; : declares a ref variable in test to a new array of 2 ints
test: a = b; : makes the ref variable a in test point to the new array => the original array is unchanged as is the a variable in main
remaining of the output is now normal.
Now case 2:
main: int[] a = new int[5]; : declares a ref variable in main pointing to a array of 5 ints
main: test(a); : calls test with a reference to the original array
test: static void test(int[] a) { : declares a ref variable a to hold a ref to the caller array => a in test is another reference to the original array
test: int[] b = new int[2]; : declares a ref variable in test to a new array of 2 ints...
test: a[i] = 1; : as a is a reference to the original array, you are changing values in the original array.
output should now be clear.

In the first code you are getting 225:
following are the reasons:
let address of a be - aa111
let address of b be - bb111
1) you are changing the address of a in the test method so in test method a address will become bb111.
2)but you are not returning the a to the main method it restores to the original address of a which is aa111.
3) you will get 222 if you return a from test method.
here is the code for that
public class Array1
{
static int[] test(int[] a)
{
int[] b = new int[2];
a = b;
System.out.print(b.length);
System.out.print(a.length);
return a;
}
public static void main(String[] args)
{
int[] a = new int[5];
a = test(a);
System.out.print(a.length);
}
}

Related

Java method returning blank array

I'm new to java and having trouble basically passing an array through to a method in another class, using the values to compute a new array, and then passing that back again to print. The problem is that when it prints the array it always prints the empty string. When I step through in debug mode I can see that the values are getting passed in and the array gets generated, but then when it prints it is always empty. It seems like somehow to code is failing to return the correct array maybe. Here is my code
public static void main(String[] args) {
double[] rnoDivs;
double[] rnoEarnings;
Company rno = new Company();
rnoDivs = new double[] {355, 355, 315, 240, 190};
rno.yearlyDividendsGrowth(rnoDivs);
rnoEarnings = new double[] {0.019, 3.451, 5.210, 3.543, 2.960};
rno.yearlyEarningsGrowth(rnoEarnings);
This is passed through to my other class
public class Company {
double[] yearlyEarningsGrowth = {};
public double[] getYearlyEarningsGrowth(){return yearlyEarningsGrowth;}
public double[] yearlyEarningsGrowth(double[] yearlyEarnings){
double[] yearlyEarningsGrowth = new double[yearlyEarnings.length];
for (int x = 0; x <= yearlyEarnings.length; x++) {
if (x < yearlyEarnings.length - 1) {
yearlyEarningsGrowth[x] = (yearlyEarnings[x] / yearlyEarnings[x + 1]) * 100;
}
}
return yearlyEarningsGrowth;
}
}
And then I try to print this statment
Company[] companies = {rno};
for(int i=0; i < companies.length; i++) {
double[] array = companies[i].getYearlyEarningsGrowth();
System.out.println("Yearly earnings growth: " + Arrays.toString(array));
}
But then I just get the array "[]". Any help with this would be appreciated! I seem to be going in circles because everything looks correct.

I getting ArrayIndexOutOfBoundsException

I am trying to convert a String array to int array and then compare elements if they are equal so far i am getting an error, first this is the method that converts string array to to int array
private static int[] convertStringArrayToIntArray(String[] strVals) {
int[] intVals = new int[strVals.length];
for (int i=0; i < strVals.length; i++) {
intVals[i] = Integer.parseInt(strVals[i]);
}
Arrays.sort(intVals);
return intVals;
}
Now the method below is where i am getting the exception
public static String ScaleBalancingCorrect(String[] strArr) {
int[] startWeights = convertStringArrayToIntArray(strArr[0].replaceAll("[^0-9,]", "").split(","));
int[] availWeights = convertStringArrayToIntArray(("0," + strArr[1]).replaceAll("[^0-9,]", "").split(","));
if (startWeights[0] != startWeights[1]) { //I get exception here
for (int i = 0; i < availWeights.length; i++) {
// omited code for brevity
this is what i was running when i got the exception
public static void main(String [] arg) {
String [] arr = {"34","1277"};
ScaleBalancingCorrect(arr);
}
Maybe it's just a typo and you wanted to write if (startWeights[0] != availWeights[1]).
availWeights will always have at least two elements, since you add 0 as a first element before the supplied other element(s).
startWeights, however, as in your example, may only have one element (in your example, it's 34).

Passing arrays between methods, and accessing them accordingly

I'm supposed to use two methods to hold arrays, then with the two arrays determine win % of the rockets, average margin of score difference for the games lost by Houston Rockets, and the lowest Houston Rockets’ score and the corresponding game number. I primarily need help with the first one, and I can get the other tasks. I just dont know how to pass arrays from methods very well. Any help would be useful, THanks!
import java.util.Scanner;
public class MorenoJonathonRocketsStatistics
{
public static void main(String[] args)
{
System.out.println("enter rockets game scores");
int[] rockets = rocketsScore();
System.out.println("enter opponents scores");
int[] opponents = opponentsScore();
int per = percent();
System.out.println("game win percent"+per+" %");
}
public static int[] rocketsScore()
{
Scanner sc = new Scanner(System.in);
int[] rocketsScore = new int[8];
for(int i=0;i<rocketsScore.length;i++)
{
rocketsScore[i] = sc.nextInt();
}
return rocketsScore;
}
public static int[] opponentsScore()
{
Scanner sc = new Scanner(System.in);
int[] opponentsScore = new int[8];
for(int i=0;i<opponentsScore.length;i++)
{
opponentsScore[i] = sc.nextInt();
}
return opponentsScore;
}
public static int percent(int[] array, int[] array2)
{
int[] rock = rocketsScore.length();
int[] opp = opponentsScore.length();
double percent=0;
int w=0, l=0;
for(int i=0; i<rocketsScore.length;i++)
{
if(rocketsScore[i]>opponentsScore[i])
{
w++;
}
else{
l++;
}
}
percent = w/l;
return percent;
}
}
To pass array in methods, you don't need to put any brackets beside the variable that is holding the array. So, you may want to do it like below:
int per = percent(rockets, opponents);

arrays of random numbers

hello everyone I got this codes but I need to make some constraint on my arrays: public static void main (String[] args)
{Random myRand = new Random ();
// Pick array size T from 1 to 100.
int T = 1 + myRand.nextInt(5);
System.out.println("T="+(T));
int C = 1 + myRand.nextInt(100);
System.out.println("C="+(C));
// Declare array of size T.
int [] production_cost=new int [T];
int []stock1= new int [T];
int[]stock2= new int [T];
int[]fix_cost1= new int [T];
int[]fix_cost2= new int [T];
int[] Demands=new int[T];
// Fill the array with random numbers.
{for (int i=0; i< T; i++){
production_cost[i] = myRand.nextInt(Integer.max(0,20));
stock1[i] = myRand.nextInt(Integer.max(0, 20));
stock2[i]= myRand.nextInt(Integer.max(0,20));
fix_cost1[i]=myRand.nextInt(Integer.max(10, 20) );
fix_cost2[i]=myRand.nextInt(Integer.max(20,30));
Demands[i] = myRand.nextInt(Integer.max(1,C));}
System.out.println("p2::"+Arrays.toString(production_cost));
System.out.println("h1::"+Arrays.toString(stock1));
System.out.println("h2::"+Arrays.toString(stock2));
System.out.println("K1::"+Arrays.toString(fix_cost1));
System.out.println("K2::"+Arrays.toString(fix_cost2));
System.out.println("d::"+Arrays.toString(Demands));
You can see this link : Fill an array with random numbers
You need to add logic to assign random values to double[] array using
randomFill method.
Change
public static double[] list(){
anArray = new double[10];
return anArray; }
To
public static double[] list() {
anArray = new double[10];
for(int i=0;i<anArray.length;i++)
{
anArray[i] = randomFill();
}
return anArray; }
Then you can call methods, including list() and print() in main method to generate random double values and print the
double[] array in console.
public static void main(String args[]) {
list(); print(); }
One result is as follows:
-2.89783865E8
1.605018025E9
-1.55668528E9
-1.589135498E9
-6.33159518E8
-1.038278095E9
-4.2632203E8
1.310182951E9
1.350639892E9
6.7543543E7

Multiple use a class

I am creating a game using an array, I have my Hunter class which looks somewhat like this ;
public static int x= 11;
public static int y =11;
public static String name = "H";`
And a method for its path using x and y.
I have declared hunter as an array in my board (2d array) class this way;
public Hunter hunters[] = new Hunter[5];
and the position of a hunter is declared in the board class as ;
a2[Hunter.x][Hunter.y] = Hunter.name;
Question: I want 5 hunters to appear on the board, how do I use the array to spawn additional 4 hunters? Thanks.
you created your array fine all you need to do is use it:
for (int i = 0; i < 5; ++i)
{
a2[hunters[i].x][hunters[i].y] = hunters[i].name
}
also, you need to make your Hunter members non-static
class Hunter
{
private int x, y;
public void setLocation(int x_, int y_)
{
x = x_; y = y_;
}
}
you get the idea :)
The static keyword (assuming you are using C++, java, C#) means that the variable is shared among all instances of the Hunter class. To allow each Hunter to have its own position, remove the static keyword and initialize them with a constructor.
I'll assume you're using Java bases on your use of String:
public class Hunter {
public int x;
public int y;
public String name;
public Hunter(int x, int y, string name) {
this.x = x;
this.y = y;
this.name = name;
}
}
Then to initialize 5 you would do
int numHunters = 5;
for (int i = 0; i < numHunters; i ++) {
hunters[i] = new Hunter(/* put x and y and name here */);
}
You can then use them to populate the board:
for (int i = 0; i < numHunters; i ++) {
Hunter h = hunters[i];
a2[h.x][h.y] = h.name;
}
You didn't specify what language you're using. That would help a bit.
At a minimum, try removing the "static" keyword from your property definitions.
In C#, your Hunter class might look like
public class Hunter
{
public int x;
public int y;
public String name;
public Hunter(int newX, int newY, String newName)
{
x = newX;
y = newY;
name = newName;
}
}
You create new Hunters using Hunter h1 = new Hunter(11, 11, "H");. Once created, you can do whatever with it.
You may want to do some reading up on Object Oriented Programming - see Intro to OOP esp sections 4.3 - 4.5 (they're short)

Resources