简体   繁体   中英

java - using elements from returned array

get1() method returns an array. I do get the output but the value from get1() is [D@addbf1

My question is there any way to directly use the returned array to get the values in inf1[0] and inf1[1] and show it in the output statement?

I am aware of other ways of showing the output. But I want to know whether I can directly retrieve elements of the returned array.

class vehicle{
   double [] inf1 = new double[2];
   void set(double d, double s) {
     inf1[0]=d;
     inf1[1]=s;
   }
   double[] get1() {
     return inf1;
   }
}

public class calc2 {
   public static void main(String args[]) {
     vehicle ob = new vehicle();
     ob.set(56.24, 75);
     System.out.println("The time taken to cover "+ob.get1());
   }
}

My question is there any way to directly use the returned array to get the values in inf1[0] and inf1[1] and show it in the output statement?

Sure:

double[] result = obj.get1();
System.out.println("Result: " + result[0] + "," + result[1]);

Or:

System.out.println("Result: " + Arrays.toString(obj.get1());

The [D@addbf1 is just the result of calling toString() on an array. If you want to get at the values within an array, you normally just access each element individually using an array index expression: array[index]

(It's not clear whether your question is really about accessing the array values, or converting an array into text for display purposes.)

Yes, you can reference the elements of the array via the get1() method:

get1()[0] will work.

try

System.out.println("The time taken to cover "+ob.get1()[0]);

ob.get1() will return your array so you can now use [index] on it.

You can use a collection class like ArrayList.

Declare ArrayList<double> inf1 = new ArrayList<double>();

In get1()

inf1.add(d);
inf1.add(s);

and in calc2, System.out.println("The time taken to cover "+ob.get1());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM