I am trying to output information with System.out.format using a double[] array as the argument. This does not work:
out.format("New dimensions:\n" +
"Length: %f\n" +
"Width: %f\n\n",
doubleArray);
This, however, does:
out.format("New dimensions:\n" +
"Length: %f\n" +
"Width: %f\n\n",
doubleArray[0], doubleArray[1]);
Why doesn't the first format work? It supposedly works with strings just fine.
Java will autobox your double to a Double, but it won't autobox your double[] to a Double[], so it doesn't match Object[]. As a result, instead of being unpacked into the Object... varargs, your array is being treated as the array itself -- which, obviously, can't be formatted as a double.
If you declare your array as Double[] instead of double[], the call to format works.
It doesn't work because an array isn't a double(in Java an array is a class, so it's like a general pointer here). You need to specify exactly what will be outputted, and you did - it's the %f format specifier. ArraySomething[] doesn't match..
See here for more on Java's Formatting and here - How does array class work in Java? , for Java arrays.
Related
I'm creating an Android app, and I'm reading some coordinates from a text file.
I'm using Integer.parseInt(xCoordinateStringFromFile) to convert the X coordinates to integers, and in the same way with the Y coordinates.
When I run the app, I get an error on that line, which looks like this:
BridgeData data = new BridgeData(
elements[0],
elements[1],
Integer.parseInt(elements[2]),
Integer.parseInt(elements[3]),
Integer.parseInt(elements[4]),
new GeoPos(Integer.parseInt(elements[5].split(",")[0]), Integer.parseInt(elements[5].split(",")[1])),
new GeoPos(Integer.parseInt(elements[6].split(",")[0]), Integer.parseInt(elements[6].split(",")[1])),
Integer.parseInt(elements[7]),
Integer.parseInt(elements[8])
);
The variable elements is a String array created by splitting the current line on every ;.
The "main" error is:
java.lang.NumberFormatException: Invalid int: "3546504756"
I wonder what this means, and how I can solve it.
Error just means that java is not able to convert the String that you are trying to use in your call to Integer.pasrseInt as that number is out of range of an integer.
You should be using Long.parseLong as 3546504756 number is out of range of an integer.
Make sure post that your BridgeData constructor accepts long as a parameter instead of integer.
Revising the concept of data type and their size might help you
http://www.tutorialspoint.com/java/java_basic_datatypes.htm
In Java, an int is 32 bits, which is enough to store numbers up to just over 2 billion. The number you were trying to read was an invalid int because it was too big.
I would seriously question the design of whatever you are doing, if you have coordinates with values of over a billion. But if you really need such big numbers, use long in place of int in your BridgeData class, and Long.parseLong in place of Integer.parseInt in the code that you quoted.
The range of int value can be lies between -2,147,483,648 to 2,147,483,647 and you are providing it more than that thats why it giving numberformatexception
You have to store the value in either long or other more range premetive type.
You can find more about java premetive data type range and value here
So, now I know that for integers I can use
System.out.println("Name: %d", Name);
So, how do I print out other values in Java? Things like Strings, Boolean, Dates, and Doubles? Do I use %d for integers only?
Regarding:
System.out.println("Name: %d", Name);
No, that won't work for println, for printf, yes, but not for println:
System.out.printf("Name: %d", Name);
or if you want a new line:
System.out.printf("Name: %d%n", Name);
For booleans, %b, for doubles, %f, for Strings %s .... Dates would require a combination of specifiers (or I would just use a SimpleDateFormat object myself). Note that these specifiers can take width constants to give them more power at formatting the output. e.g.,
System.out.printf("Pi to four places is: %.4f%n", Math.PI);
Please check the Formatter API for more of the details.
System.out.println(whatever);
whatever can be a String, boolean, int, Point, whatever. Check out the docs.
You can do System.out.println("something"); if you want to skip a line after printing, but if you want to print something, then continue on the same line, then you should just do System.out.print("something"); You can also just print out Strings, boolean values (t/f) and doubles just by doing something like
System.out.println(booleanname); or
System.out.println(Stringname; or
System.out.println(doublevariablename);
Anything you put inside the parenthesis of System.out.println() or System.out.print() is formatted and printed as a string. However, you can control how variables are printed out inside your string (as you did using %d) using Java's printf() method.
The printf() method takes two parameters: the string to print and a list of variable names. You insert the format flags (%d, %f, etc) in the string and you list the variables you want formatted in the string second.
System.out.printf("Your total is %d", 29.99);
This means that Java will format 29.99 as a decimal rather than a string when it outputs "Your total is 29.99".
You can check out the other types of formatting in the "conversion type character" table here.
I am using an x:forEach to loop through an XML object to extract data
In the x:forEach I am using x:set to select the values I want.
<x:forEach var="data" select="$path/">
<x:set var="dataPoint" select="string($data//cell[8]/text())" /> ...
As you can see, I am selecting the text within the specified node and then casting it into a string. The dataPoint variables are in fact numbers, and I need to do certain things to them such as sorting and extracting the min and max amounts.
The problem is I am trying to form an Array of integers and my compiler is complaining that I cannot convery an Object into an int.
The error is: " Type mismatch: cannot convert from Object to int "
Any thoughts?
Thanks
Solution:
I cast the Object into a String and then from a String to an integer:
Integer.parseInt(StringVar);
Whenever I try to print the char arrays to the console, I'm getting the result in integer format, but whenever I try to print integer arrays to the console, I'm getting the result in hashcode format. Could anyone please tell me why?
char[] arr={'4','5','6'};
System.out.println(arr); //456
int[] arr={4,5,6};
System.out.println(arr) //[I#3e25a5]
java.io.PrintStream (the class of System.out) has a special print-method for char[], but not for int[]. So for the char[], this special method is used, while int[] is printed via the generic version, which prints the hashcode (or, to be more precise, the result of String.valueOf() called with the object as parameter).
Simply because there's no method for which handles int[] specially. It would be printed by String#valueOf() instead which implicitly calls Object#toString(). If the Object#toString() isn't overridden in the given object type, then the following will get printed (as per the aforelinked API).
getClass().getName() + '#' + Integer.toHexString(hashCode())
The int[] class has a name of [I.
To achieve what you want, you need Arrays#toString() instead:
int[] arr = {4, 5, 6};
System.out.println(Arrays.toString(arr)); // [4, 5, 6]
In the first case the character array is just used like a string (which is in fact also just an array of characters).
In the second it has no overload for the type of integer array and just prints out the object reference.
I think that the first one is treated as a CharSequence... like a String.
I have an array of floats and I would like to convert it to an array of doubles in Java. I am aware of the obvious way of iterating over the array and creating a new one. I expected Java to digest a float[] smoothly where it wishes to work with double[]... but it can not work with this.
What is the elegant, effective way of doing this conversion?
Basically something has to do the conversion of each value. There isn't an implicit conversion between the two array types because the code used to handle them after JITting would be different - they have a different element size, and the float would need a conversion whereas the double wouldn't. Compare this to array covariance for reference types, where no conversions are required when reading the data (the bit pattern is the same for a String reference as an Object reference, for example) and the element size is the same for all reference types.
In short, something will have to perform conversions in a loop. I don't know of any built-in methods to do this. I'm sure they exist in third party libraries somewhere, but unless you happen to be using one of those libraries already, I'd just write your own method. For the sake of convenience, here's a sample implementation:
public static double[] convertFloatsToDoubles(float[] input)
{
if (input == null)
{
return null; // Or throw an exception - your choice
}
double[] output = new double[input.length];
for (int i = 0; i < input.length; i++)
{
output[i] = input[i];
}
return output;
}
In Java 8 you can, if you really want to, do:
IntStream.range(0, floatArray.length).mapToDouble(i -> floatArray[i]).toArray();
But it's better (cleaner, faster, better semantics) to use Jon Skeet's function.
Do you actually need to copy your float array to a double array? If you are having trouble with the compiler and types when using the floats you can use this...
float x = 0;
double d = Double.valueOf(x);
What advantage do you get by taking a copy? If you need greater precision in the results of computations based on the floats then make the results double. I can see quite a lot of downsides to having a copy of the array, and performing the copy function, especially if it is large. Make sure you really need to do it.
HTH