'Returning array to from static method to main method. Array printing gibberish [duplicate]
Hey all I am stuck with this homework assignment and hoping to print numbers in the main that were inputted from a static method. I have tried two options....this one just prints gibberish
Option 1: But this prints gibberish.
public class GetNumbers {
public static void main(String[] args) {
System.out.println(" Congratulations, you entered two valid floats:" + getTwoFloats());
}
// Return method to obtain two values from user============================================
private static float [] getTwoFloats() {
float [] myResults =new float[2];
Scanner readInput = new Scanner(System.in);
do {
System.out.print("\nEnter two floats separated by a space: ");
try {
float myFloat1 = readInput.nextFloat();
// waits for user input
float myFloat2 = readInput.nextFloat();
// waits for user input if you are here, the floats were good, you
// are done, break out from loop
} catch (final InputMismatchException e) {
System.out.println("You have entered an invalid input. Try again.");
readInput.nextLine();
// discard non-float input
continue;
// keep looping until you found right one
}
return myResults;
} while (true);
}
Solution 1:[1]
The toString impl of arrays is not what you think it is. Calling System.out.println(x) where x is just some object is shorthand for System.out.println(x.toString()).
You can either write your own, or use Arrays.toString(x) instead: System.out.println(Arrays.toString(getTwoFloats()).
In general arrays are low level constructs with many annoying downsides and few upsides. You shouldn't use them for this sort of purpose. a List<Double> would be a better idea.
NB: float is completely useless. Use double.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rzwitserloot |
