So I was trying to write a function for a ragged array; I may have got this entirely wrong, if so please explain why/how I went wrong. It took me ages to get this far and I have a feeling I've alreayd done it wrong.
I tried compiling it because I'm pretty sure currently it will work, however i'm getting the error "variable n may not have been initialized". My code so far is:
static double[][] exampleMatrix()
{
int n;
double[][] a = new double [3][];
a[0] = new double[n-1];
a[1] = new double[n];
a[2] = new double[n-1];
{
for (int i = 0; i < n-1; i++)
{
a[0][i] = 1;
a[2][i] = 1;
}
for (int i = 0; i < n; i++)
{
a[1][i] = - i - 1;
}
return a;
}
}
I'm probably missing something really really obvious, but i'm not sure what it is to initialize n.
EDIT: I have been told to make this work for a value n that is not yet given.. How would I do that? As in, the user is supposed to input the value of n, and be given an array in return.
Basically, my given question is to implement a function exampleMatrix that, given n, produces the array where all values in teh array a[0] is 1, and same for a[2], and then for a[1], be given a range of values from -1 down to -n for a[1][n-1]. This is what I have so far to calculate this, but I am guessing I have gone completely wrong?
You don't set any value to n. How will your program know how big to make the arrays and how many iterations to run in the for loops?
Method variables (unlike fields) cannot rely on the default value (0 in this case). As such n is not anything when it is declared
int n;
You need to state what n is at some point between declaring it and using it, for example.
int n;
n=7;
or
int n=7;
n not known at compile time
You can also pass n as a variable, if n is variable
static double[][] exampleMatrix(int n){
double[][] a = new double [3][];
a[0] = new double[n-1];
a[1] = new double[n];
a[2] = new double[n-1];
{
for (int i = 0; i < n-1; i++)
{
a[0][i] = 1;
a[2][i] = 1;
}
for (int i = 0; i < n; i++)
{
a[1][i] = - i - 1;
}
return a;
}
}
This method would then be used as
double[][] someMatrix= exampleMatrix(5); //<-- 5 is passed into the function and becomes n
Or you can calculate n in whatever way you see fit
Actually the Problem is with local variable
int n;
The scope of local variables is much narrower. Compiler knows when its getting used. Hence, forcing programmer to initialize the variable
You have to initialize it with any default value as int n=0;
I want to complement the above responses.
You have to take care with the static segments, because when a class load its static segments, the class don't assign default value, if you type:
public static int n;
in your class, the value depends on the programmer. this can throw an exception about initialized.
Related
I have a question about my code.
class Zillion
{
private int[] d;
public Zillion(int size)
{
d = new int[size];
}
public void timesTen()
{
for(int i = 0; i<d.length;i++)
{
d[i] = d[i + 1];
}
d[d.length]=0;
}
public String toString()
{
String num;
num= "";
for(int i = 0; i<d.length; i++)
{
num = num + d[i];
}
return num;
}
}
Here in my class Zillion, I am trying to multiply a number that is represent by an array by 10. So what I did was I move the elements at each index to the left and change the value at the last index to 0. For instance,
0 1 4 8 will be come 1 4 8 0.
I am not sure whether my logic will work but that was my first start.
First, I am trying to change the values at each index of the array with an assigned size and here is my driver file.
class Driver
{
public static void main(String[] args)
{
Zillion z = new Zillion(5);
System.out.println(z); // 00000
for (int j = 0; j <= 5; j += 1)
{
z[j]=j;
}
System.out.println(z);
}
}
However, Java throws me an error and says: "Error:(32, 14) java: array required, but Zillion found".
I took C++ and I believe I could change array values like z[j] = j but I guess it is different in Java.
Is there a way I can change the values of the specific index I want? The reason why I used the for loop is because I could not think of any method that I can use to assign the values at each index I want. Is that possible that in the Driver file I create an array, say, 0148 and call my "timesTen" method to give me what I want?
Thank you!
You need to expose the array d of zillion class using a gettor method.
public getArray(){ return d;}
Instead of z[j]=j; you need to use z.getArray()[j] = j
Also your timesTen method will cause arrayindex out of bounds exception in the line
d[d.length]=0;
Java array is not dynamically growing so, Index should be lesser than array size.
You can't index a class, only arrays.
Define a method in Zillion
class Zillion {
public void set(int index, int value) {
// TODO implement
}
}
In your loop, call z.set(j, j)
Note: j <= 5 will cause an out of bound exception
I believe I could change array values like z[j] = j
You could - if z would be an array! But, as the error message also states, it is an object of type Zillion:
Zillion z = new Zillion(5);
You are using instance z of Zillion class, use array instead of it.
//Create getter method in Zillion Class
public int[] getD() {
return d;
}
//And access that array in Driver Class
int[] array = z.getD();
for (int j = 0; j < 5; j += 1) {
array[j] = j;
}
Moreover, you are going to face an
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
because of the statement d[d.length] = 0; in your timesTen() implementation. You have to replace that line with:
d[d.length-1] = 0;
This is not an answer to your question, because you have already received valuable ones, but I hope it could help you.
public int[] selectionSort(int array[]) {
for(int i = array.length - 1; i >= 0; i--) {
int highestIndex = i;
for(int j = i; j >= 0; j--) {
if(array[j] > array[highestIndex])
highestIndex = j;
}
int temp = array[i];
array[i] = array[highestIndex];
array[highestIndex] = temp;
}
return array;
}
I understand the concept of selection sort, but the code is confusing me. Specifically, can someone explain what is happening in the last three statements of the outer for-loop starting with "int temp = array[i];"
This is the famous swapping routine. In languages like Java, when you want to swap the values of two variables named say a and b, you have to resort to such a routine where you use a third variable to hold a value in transit:
int a = 2;
int b = 6;
int tmp = a; // now tmp has a value that is _copy_ of a i.e. 2
a = b; // since we saved a in tmp, we can _mutate_ it, now a has b's value
b = tmp; // swap! here, b = a won't work because a contains b's current value.
// now a has value 6 and b has value 2, exactly what we wanted.
In some other languages, a construct like a, b = b, a is available for this purpose, which is more intuitive in my opinion.
In selection sort, after the inner loop has found the index of the element that holds the highest value, you need to swap it with the element held by the outer loop index and that's what this achieves in that context.
Help! I have this school assignment that wants me to write a method to find the area of rectangles (an array of ints) by multiplying width (an ArrayList) by length (an array of doubles). I'm very very new to coding; I've tried for over five hours to get this working, but I keep doing things wrong and I simply can't get it right. This is the code for the method that I've written:
public void calcRectangleArea(int index, ArrayList width, double[] length, int[] area)
{
double temp = length[index];
for(index = 0; index < length.length; index++)
{
for(index = 0; index < width.size(); index++)
{
Object widthObj = (int)width.get(index);
area[index] = temp * widthObj;
}
}
}
The full starter code we were given is here, if you need more context (it's commented): http://pastie.org/pastes/916496
Thank you so much for any help you can give me in writing this method. I've been working for hours and I just can't get it...
The length of the array and size of the arraylist should be same , And you have to change the method logic a bit, Have a look at the below code snippet
public static int[] calcRectangleArea(List<Double> width, double[] length)
{
int[] area=new int[length.length];
for(int index = 0; index < length.length; index++)
{
area[index] = (int) (length[index]*width.get(index));
}
return area;
}
Call this method passing width arraylist and length array. It will return area array of ints
You dont really need two loops here. Assuming that width[1] correlates to length[1] you can just loop through both collections at the same time in the same loop.
This should work (i haven't written a line of java in ~2 years so it may not be 100%)
public void calcRectangleArea(int index, ArrayList width, double[] length, int[] area)
{
//assuming length.length == width.size
for(index = 0; index < length.length; index++)
{
int anArea = (int)(width.get(index) * length[index]);
area[index]=anArea;
}
}
again the code above assumes the size of the collections are the same.
Firstly, you don't need to assign temporary variables:
double temp = length[index];
...
Object widthObj = (int)width.get(index);
Since you will only reference them once. Reference them directly instead:
area[index] = length[index] * (int)width.get(index);
Secondly, your for loops are unneeded, and they are declared wrong. You're trying to increment the index (and twice nonetheless) that was passed to the function which will cause problems. If you were to use nested for loops, you would declare a new iterator variable for each of them:
for (int i = 0; i < something; i++) {
for (int j = 0; j < somethingElse; j++) {
doSomething();
}
}
However in this case you don't even need them.
In addition, you should not have created an Object when you wanted to cast an int:
Object widthObj = (int)width.get(index);
should have been
int width = (int)width.get(index);
However again, this line is unnecessary, and you shouldn't be casting to int this early.
Ultimately, all you need to do is the one line:
area[index] = (int)(length[index] * width.get(index));
public void zero() {
int sum = 0;
for (int i = 0; i < mArray.length; ++i) {
sum += mArray[i].mSplat;
}
}
public void one() {
int sum = 0;
Foo[] localArray = mArray;
int len = localArray.length;
for (int i = 0; i < len; ++i) {
sum += localArray[i].mSplat;
}
}
According to Android documentation, in above code, zero is slower. But I don't understand why ? well I haven't learn that much deep but as I know length is a field not method. So when loop retrieves its value, how its different from retrieving from local variable ? and array length is always fixed once initialized. What am I missing ?
Well I guess this is because at zero, he always needs to retrieve the information from mArray and in one, he has it accessible. This means, zero needs two "methods":
Access mArray
Access mArray.length
But one only needs one "methods":
Access len
In the first example, the JVM needs to first fetch the reference to the array and then access its length field.
In the second example, it only accesses one local variable.
On desktop JVMs this is generally optimised and the two methods are equivalent but it seems that Android's JVM does not do it... yet...
It is a matter of scope. Accessing an instance variable is slower than a method variable because it is not stored in the same memory places. (because method variables are likely to be accessed more often).
Same goes for len, but with an extra optimization. len cannot be changed from outside the method, and the compiler can see that it will never change. Therefore, its value is more predictable and the loop can be further optimized.
public void zero() {
int sum = 0;
for (int i = 0; i < mArray.length; ++i) {
sum += mArray[i].mSplat;
}
}
Here if you look at the for loop array length is calculated for every iteration, that degrades
the performance.
public void one() {
int sum = 0;
Foo[] localArray = mArray;
int len = localArray.length;
for (int i = 0; i < len; ++i) {
sum += localArray[i].mSplat;
}
}
In this case the length is calculated before for loop and then used in the loop.
I have the following ArrayList
ArrayList<double[]> db_results = new ArrayList<double[]>();
Which is populated by the following loop
double[] nums = new double[3];
for ( int i = 0 ; i <= 2; i++) {
double val = Double.parseDouble(i);
nums[i] = val;
}
db_results.add(nums);
How can i add the values from the same position in each array to make another array??
So 1+1+1=3 would be position one of the new array 2+2+2=6 would be position two of the new array and 3+3+3=9 would be position three of the new array??
Cheers
A nested loop would do it.
I would encourage you to take the time to do a Java tutorial or read a textbook. This is really basic stuff, and you'd do better learning the language properly than learning by trial and error interspersed with random SO questions.
By the way, this line from your code won't compile:
double val = Double.parseDouble(i);
The i variable is declared as an int and the parseXxx methods take a String argument. To convert an int to double, just assign it:
double val = i;
This might be what you're looking for:
double[] newArray = new double[3];
for (double[] array : db_results) {
for (int i = 0; i < 3; ++i) {
newArray[i] += array[i];
}
}
It will work after db_results has been populated. You can also compute the sum array at the same time that db_results is being populated using slukian's method.
Either a java math function or a nested loop its for your answer. Try yourself its just a mathematical calculation.