-2

I was tasked with having an array that starts with size 10, then have user input heights in inches and stores it inside the array and then a new array converts all of those elements inside the initial array to cm. I have absolutely no idea what to do and really need help. How do I fix this?

double[] heightInches = new double[10];
int currentSize = 0;
Scanner in = new Scanner(System.in);
System.out.print("Please enter heights (inches), Q to quit: ");
 while (in.hasNextDouble() && currentSize < heightInches.length)
  {  
     heightInches[currentSize] = in.nextDouble();
     currentSize++;
  }

     double[] result = convert(heightInches);

System.out.println("Heights in cm: " + result);
}

public static double[] convert(double[] inches) {

 double heightCm[] = new double[inches.length];

 for( int i = 0; i < inches.length; i++)
 {
     heightCm[i] = inches[i] * 2.54;
 }


    return heightCm;
}



}
sparkles
  • 59
  • 1
  • 1
  • 10
  • 1
    It is not clear what exactly are you asking. – Alex Weitz Mar 10 '16 at 18:33
  • i am asking how can I fix my code to do the intended task of converting my initial array of 10 user inputted heights in heights, to cm, saving these new converted values into a new array, and then displaying the new array. – sparkles Mar 10 '16 at 18:35
  • Please note: don't try to resolve all of your assignment in one shot. Go step by step. Write code, compile, run. See what is going on. Instead of just throwing parts of your code at us; and then expecting us to digest that; and spend a lot of time to understand what is going on. – GhostCat Mar 10 '16 at 18:43

3 Answers3

0

You can just print an array, as it will print the Object address. You can instead try:

for (double res:result) {
    System.out.println("Heights in cm: " + res);
}

You can also print the whole array at once using Arrays.toString();

System.out.println("Heights in cm: " + Arrays.toString(result));
Alex Weitz
  • 3,199
  • 4
  • 34
  • 57
  • thank you this worked! however, so I can understand for the future, whenever I want to print an array I have to use a for loop? – sparkles Mar 10 '16 at 18:50
  • A loop is just the simplest method you can use to go through every cell in an array. Depends on what exactly you're seeking, there are other methods of printing an array. You can read this: http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array – Alex Weitz Mar 10 '16 at 18:57
0

Besides the fact that your code is incomplete and hard to read because you didn't spend the time to format it nicely ... it is almost complete.

The only problem is that

System.out.println("Heights in cm: " + result);

does not print the array content. It prints the reference to the array. Instead you have to iterate (using a for loop for example) to print each array entry one by one.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

System.out.println("Heights in cm: " + Arrays.toString(result));

jonhid
  • 2,075
  • 1
  • 11
  • 18