Posts

Showing posts with the label double

Convert double to int array

I have a double double pi = 3.1415; I want to convert this to a int array int[] piArray = {3,1,4,1,5}; I came up with this double pi = 3.1415; String piString = Double.toString(pi).replace(".", ""); int[] piArray = new int[piString.length()]; for (int i = 0; i <= piString.length()-1; i++) piArray[i] = piString.charAt(i) - '0'; It's working but I don't like this solution because I think a lot of conversions between datatypes can lead to errors. Is my code even complete or do I need to check for something else? And how would you approach this problem? I don't know straight way but I think it is simpler: int[] piArray = String.valueOf(pi) .replaceAll("\\D", "") .chars() .map(Character::getNumericValue) .toArray(); Since you want to avoid casts, here's the arithmetic way, supposing you only have to deal with positive numbers...

Getting unwanted NullPointerException in ternary operator - Why?[duplicate]

This question already has an answer here: Short form for Java If statement returns NullPointerException when one of the returned objects is null [duplicate] 3 answers While executing the following code, I am getting a NullPointerException at line: value = condition ? getDouble() : 1.0; In earlier lines when I use null instead of getDouble() everything works and this is strange. public class Test { static Double getDouble() { return null; } public static void main(String[] args) { boolean condition = true; Double value; value = condition ? null : 1.0; //works fine System.out.println(value); //prints null value = condition ? getDouble() : 1.0; //throws NPE System.out.println(value); } } Can someone help me understand this behavior? When you write value = condition ? null : 1.0; the type of condition ? null : 1.0 must be a reference type, so the type is Double, which can hold the value null. When you write value = condi...