Explanation
You should replace it with:
d[i] = Double.valueOf(d.length - i);
From its Javadoc:
Deprecated.
It is rarely appropriate to use this constructor. The static factory
valueOf(double)is generally a better choice, as it is likely to yield significantly better space and time performance.
In general, valueOf is not forced to always return a new instance. It can utilize an internal cache and re-use values created before already, which makes it faster. For example if you create hundreds of 1.0.
Note
Is there a specific reason you are using a Double[] in the first place? If not, go for double[] instead. The primitives are much faster and have less memory overhead, compared to their object wrapper.
Then your code is just:
double[] d = new double[10];
for (int i = 0; i < d.length; i++)
d[i] = d.length - i;
By the way, you should prefer to never omitt the curly braces. Even if your loop is just one line. This is a very common source for bugs that are hard to find.
Also, your variable naming is not very good. What is d? Try to give it a name that reflects what it actually means. Like ages if it stores person ages, for example. If you do not have something specific, maybe use values. That is already better than just d. Especially since it is plural, so it is clear that it is an array of multiple values.
double[] values = new double[10];
for (int i = 0; i < values.length; i++) {
values[i] = values.length - i;
}
Answer from Zabuzard on Stack OverflowExplanation
You should replace it with:
d[i] = Double.valueOf(d.length - i);
From its Javadoc:
Deprecated.
It is rarely appropriate to use this constructor. The static factory
valueOf(double)is generally a better choice, as it is likely to yield significantly better space and time performance.
In general, valueOf is not forced to always return a new instance. It can utilize an internal cache and re-use values created before already, which makes it faster. For example if you create hundreds of 1.0.
Note
Is there a specific reason you are using a Double[] in the first place? If not, go for double[] instead. The primitives are much faster and have less memory overhead, compared to their object wrapper.
Then your code is just:
double[] d = new double[10];
for (int i = 0; i < d.length; i++)
d[i] = d.length - i;
By the way, you should prefer to never omitt the curly braces. Even if your loop is just one line. This is a very common source for bugs that are hard to find.
Also, your variable naming is not very good. What is d? Try to give it a name that reflects what it actually means. Like ages if it stores person ages, for example. If you do not have something specific, maybe use values. That is already better than just d. Especially since it is plural, so it is clear that it is an array of multiple values.
double[] values = new double[10];
for (int i = 0; i < values.length; i++) {
values[i] = values.length - i;
}
From Java 9 constructor(s) method(s) was Deprecated
Deprecated. It is rarely appropriate to use this constructor. The static factory
valueOf(double)is generally a better choice, as it is likely to yield significantly better space and time performance. Constructs a newly allocated Double object that represents the primitive double argument.
So replace with:
Double.valueOf(d.length - i)
Hi, So after changing in program the Gross and netSalary to BigDecimal, I got lots of errors and it is not clear how I can fix them. So first of all in the main, I want to print the sum of all netSalaries paid, however when I changed it to BigDecimal it is saying that I cannot apply '+' to java.math.BigDecimal and I really can't find a solution for it. Secondly, my getEmployeeGrossSalary in the superclass RegularEmployees is highlighted and it says that the method recurses infinitely and can only end by throwing an exception and when I run the program I am getting a stackOverflow error because I am calling it in the main to print all salaries from highest to lowest, so why was everything fine when the type was double and how can I fix these errors? Thanks in advance!
import java.math.BigDecimal;
import java.math.RoundingMode;
public class RegularEmployees { //superclass
protected double employeeGrossSalary;
RegularEmployees(double employeeGrossSalary) {
this.employeeGrossSalary = employeeGrossSalary;
}
public BigDecimal employeeNetSalary() {
return new BigDecimal(this.employeeGrossSalary - (this.employeeGrossSalary * 0.1)).setScale(2,RoundingMode.DOWN);
}
public BigDecimal getEmployeeGrossSalary() { //the method here is highlighted and it says that getEmployeeGrossSalary recurses infinitely and can only end by throwing an exception.
return new
BigDecimal(String.valueOf(this.getEmployeeGrossSalary())).setScale(2,RoundingMode.DOWN);
}
}
import java.math.BigDecimal;
import java.math.RoundingMode;
public class ManagerEmployees extends RegularEmployees { //Subclass
private String managerDegree;
ManagerEmployees(double employeeGrossSalary, String managerDegree) {
super(employeeGrossSalary);
this.managerDegree = managerDegree;
public BigDecimal getEmployeeGrossSalary() {
return new
BigDecimal(String.valueOf(this.getEmployeeGrossSalary())).setScale(2,RoundingMode.DOWN);
}
@Override
public BigDecimal employeeNetSalary(){
return new BigDecimal(super.employeeGrossSalary - (super.employeeGrossSalary * 0.1)).setScale(2, RoundingMode.DOWN);
}
@Override
public BigDecimal getEmployeeGrossSalary() {
BigDecimal grossSalaryWithBonus = BigDecimal.valueOf(0.00);
if (this.managerDegree.equals("BSc")) {
grossSalaryWithBonus = new BigDecimal(super.employeeGrossSalary - (super.employeeGrossSalary * 0.1)).setScale(2, RoundingMode.DOWN);
} else {
if (this.managerDegree.equals("MSc")) {
grossSalaryWithBonus = new BigDecimal(super.employeeGrossSalary -(super.employeeGrossSalary * 0.2)).setScale(2, RoundingMode.DOWN);
} else {
if (this.managerDegree.equals("PhD")) {
grossSalaryWithBonus = new BigDecimal(super.employeeGrossSalary + (super.employeeGrossSalary * 0.35)).setScale(2, RoundingMode.DOWN);
}
}
}
return grossSalaryWithBonus;
}
}
import java.util.Comparator;
import java.util.ArrayList;
import java.math.BigDecimal;
public class Main { //main class
public static void main(String[] args){
ArrayList<RegularEmployees> employeesList = new ArrayList<>();
BigDecimal totalNetSalaries = BigDecimal.valueOf(0.00);
for (RegularEmployees currentEmployee : employeesList) {
totalNetSalaries = BigDecimal.valueOf(totalNetSalaries + currentEmployee.employeeNetSalary()); //Bug here ; Operator "+" cannot be applied to 'java.math.BigDecimal','java.math.BigDecimal' how can I fix it?
}
System.out.println(totalNetSalaries);
employeesList.sort(Comparator.comparing(RegularEmployees::getEmployeeGrossSalary).reversed());
for(RegularEmployees current : employeesList){
System.out.println(current.getEmployeeGrossSalary());
}Double parameter can be null when double can't.
First off you need to understand the difference between the two types.
double is a primitive type whereas Double is an Object.
The code below shows an overloaded method, which I assume is similar to your lab code.
void doStuff(Double d){ System.out.println("Object call"); }
void doStuff(double d){ System.out.println("Primitive call"); }
There are several ways you can call these methods:
doStuff(100);
doStuff(200d);
doStuff(new Double(100));
These calls will result in:
"Primitive call"
"Primitive call"
"Object call"
You are taking the ASCII value of each character e.g. '1' => 49 and pushing it on to the stack.
Most likely what you want is to use a Scanner to read numbers converted from the text you input.
Replace:
number = postfix.charAt(pos);
with:
number = Double.parseDouble(Character.toString(postfix.charAt(pos)));
The Double.parseDouble method converts the string in double:
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
(from Javadoc)
If you split the String with postfix.toString.split(" ") and then iterate on the string[] you will be able to parse also double values (like "8.4567"):
String[] sa = postfix.toString().split(" ");
for (String string : sa) {
.... omissis ...
otherwise your code will be correct only parsing single digit integer values.
This is array initializer syntax, and it can only be used on the right-hand-side when declaring a variable of array type. Example:
int[] x = {1,2,3,4};
String[] y = {"a","b","c"};
If you're not on the RHS of a variable declaration, use an array constructor instead:
int[] x;
x = new int[]{1,2,3,4};
String[] y;
y = new String[]{"a","b","c"};
These declarations have the exact same effect: a new array is allocated and constructed with the specified contents.
In your case, it might actually be clearer (less repetitive, but a bit less concise) to specify the table programmatically:
double[][] m = new double[4][4];
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
m[i][j] = i*j;
}
}
You can initialize an array by writing actual values it holds in curly braces on the right hand side like:
String[] strArr = { "one", "two", "three"};
int[] numArr = { 1, 2, 3};
In the same manner two-dimensional array or array-of-arrays holds an array as a value, so:
String strArrayOfArrays = { {"a", "b", "c"}, {"one", "two", "three"} };
Your example shows exactly that
double m[][] = {
{0*0,1*0,2*0,3*0},
{0*1,1*1,2*1,3*1},
{0*2,1*2,2*2,3*2},
{0*3,1*3,2*3,3*3}
};
But also the multiplication of number will also be performed and its the same as:
double m[][] = { {0, 0, 0, 0}, {0, 1, 2, 3}, {0, 2, 4, 6}, {0, 3, 6, 9} };
Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).
This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.
Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).
Resurrecting the dead here, but just in case someone stumbles against this like myself. I know where to get the maximum value of a double, the (more) interesting part was to how did they get to that number.
double has 64 bits. The first one is reserved for the sign.
Next 11 represent the exponent (that is 1023 biased). It's just another way to represent the positive/negative values. If there are 11 bits then the max value is 1023.
Then there are 52 bits that hold the mantissa.
This is easily computed like this for example:
public static void main(String[] args) {
String test = Strings.repeat("1", 52);
double first = 0.5;
double result = 0.0;
for (char c : test.toCharArray()) {
result += first;
first = first / 2;
}
System.out.println(result); // close approximation of 1
System.out.println(Math.pow(2, 1023) * (1 + result));
System.out.println(Double.MAX_VALUE);
}
You can also prove this in reverse order :
String max = "0" + Long.toBinaryString(Double.doubleToLongBits(Double.MAX_VALUE));
String sign = max.substring(0, 1);
String exponent = max.substring(1, 12); // 11111111110
String mantissa = max.substring(12, 64);
System.out.println(sign); // 0 - positive
System.out.println(exponent); // 2046 - 1023 = 1023
System.out.println(mantissa); // 0.99999...8
If you don't mind using a 3rd party library, commons-lang has the ArrayUtils type with various methods for manipulation.
Double[] doubles;
...
double[] d = ArrayUtils.toPrimitive(doubles);
There is also the complementary method
doubles = ArrayUtils.toObject(d);
Edit: To answer the rest of the question. There will be some overhead to doing this, but unless the array is really big you shouldn't worry about it. Test it first to see if it is a problem before refactoring.
Implementing the method you had actually asked about would give something like this.
double[] getDoubles(int columnIndex) {
return ArrayUtils.toPrimitive(data[columnIndex]);
}
In Java 8, this is one-liner:
Double[] boxed = new Double[] { 1.0, 2.0, 3.0 };
double[] unboxed = Stream.of(boxed).mapToDouble(Double::doubleValue).toArray();
Note that this still iterates over the original array and creates a new one.
Try this:
List<Double> list = Arrays.asList(1.38, 2.56, 4.3);
which returns a fixed size list.
If you need an expandable list, pass this result to the ArrayList constructor:
List<Double> list = new ArrayList<>(Arrays.asList(1.38, 2.56, 4.3));
Try this,
ArrayList<Double> numb= new ArrayList<Double>(Arrays.asList(1.38, 2.56, 4.3));
You can try BigDecimal for this purpose
Double toBeTruncated = new Double("3.5789055");
Double truncatedDouble = BigDecimal.valueOf(toBeTruncated)
.setScale(3, RoundingMode.HALF_UP)
.doubleValue();
You can't set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don't have decimal digits. They have binary digits.
You will have to convert into a decimal radix, either via BigDecimal or DecimalFormat, depending on what you want to do with the value later.
See also my answer to this question for a refutation of the inevitable *100/100 answers.
The problem is that you compare top to array.length but then you assign array[++top], the index is greater by one. When top is array.length - 1 it's still less than array.length, therefore else branch is chosen, but ++top is out of bounds.
The top index goes from 0 to 9. So just adjust your if condition like this, and you should be good to go.
if (top >= array.length -1) {
double overflows to Infinity and -Infinity, it doesn't wrap around. BigDecimal doesn't overflow, period, it is only limited by the amount of memory in your computer. See: How to get biggest BigDecimal value
The only difference between + and .addExact is that it attempts to detect if overflow has occurred and throws an Exception instead of wraps. Here's the source code:
public static int addExact(int x, int y) {
int r = x + y;
// HD 2-12 Overflow iff both arguments have the opposite sign of the result
if (((x ^ r) & (y ^ r)) < 0) {
throw new ArithmeticException("integer overflow");
}
return r;
}
If you want to check that an overflow has occurred, in one sense it's simpler to do it with double anyway because you can simply check for Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY; in the case of int and long, it's a slightly more complicated matter because it isn't always one fixed value, but in another, these could be inputs (e.g. Infinity + 10 = Infinity and you probably don't want to throw an exception in this case).
For all these reasons (and we haven't even mentioned NaN yet), this is probably why such an addExact method doesn't exist in the JDK. Of course, you can always add your own implementation to a utility class in your own application.
The reason you do not need a addExact function for floating point digits is because instead of wrapping around, it overflows to Double.Infinity.
Consequently you can very easily check at the end of the operation whether it overflowed or not. Since Double.POSITIVE_INFINITY + Double.NEGATIVE_INFINITY is NaN you also have to check for NaN in case of more complicated expressions.
This is not only faster but also easier to read. Instead of having Math.addExact(Math.addExact(x, y), z) to add 3 doubles together, you can instead write:
double result = x + y + z;
if (Double.isInfinite(result) || Double.isNan(result)) throw ArithmeticException("overflow");
BigDecimal on the other hand will indeed overflow and throw a corresponding exception in that case as well - this is very unlikely to ever happen in practice though.
String.format("%1$,.2f", myDouble);
String.format automatically uses the default locale.
String.format("%4.3f" , x) ;
It means that we need total 4 digits in ans , of which 3 should be after decimal . And f is the format specifier of double . x means the variable for which we want to find it . Worked for me . . .
The only possibilities you have are:
Type cast the
doubleinto anintif you want to store your number as an integer:int a = (int)26.4 // so a will be 26(you will obviously lose precision this way)
Store the number as a
doubleto keep the precision:double a = 26.4
Casting will not help at anything, look at the code below:
//int a = 26.4; // gives compile error
int a = (int) 26.4; // gives 26
double b = a; // gives 26.0
double c = (double) a; // also gives 26.0
I've linked my function here
For one of my assignments, I'm supposed to be creating a binary search function using recursion. I'm supposed to be testing it with arrays of up to a size of 250,000 integers.
I've been getting "Exception in thread "main" java.lang.StackOverflowError" on line 15, which is one of the lines of recursion, so I assume it's something to do with the recursion itself, though I'm not quite sure what the issue is.
If someone could explain what I'm doing wrong and how to go about fixing it, that would be great!
You can use Double.parseDouble() to convert a String to a double:
String text = "12.34"; // example String
double value = Double.parseDouble(text);
For your case it looks like you want:
double total = Double.parseDouble(jlbTotal.getText());
double price = Double.parseDouble(jlbPrice.getText());
If you have problems in parsing string to decimal values, you need to replace "," in the number to "."
String number = "123,321";
double value = Double.parseDouble( number.replace(",",".") );