I've got to create a code in Java for a homework assignment displaying a salary starting at 1 cent and doubling daily for 10 days. My only problem is that I'm having trouble converting the salary into decimal format and my output is coming out in dollars, not cents. I'm very new to coding and can use any help I can get. My error is that "salary" is already defined in the main, but when i move the decimal format code above the main the problem still exists. How do I move the decimal place over two places? My output is posted under the code so you guys can see my problem. Thank you!!
import java.util.Scanner;
import java.text.DecimalFormat;
public class hw2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//Find number of days worked
int days;
System.out.println("How many days did you work under the current
salary?");
days = in.nextInt();
int num = 1;
while (num <= days)
{
double salary = Math.pow(2, (num-1));
DecimalFormat salary = new DecimalFormat("##.00");
System.out.println("Your salary for day " + num + " is $" +
salary);
num++;
}
}
}
Output:
How many days did you work under the current salary?
10
Your salary for day 1 is $1.0
Your salary for day 2 is $2.0
Your salary for day 3 is $4.0
Your salary for day 4 is $8.0
Your salary for day 5 is $16.0
Your salary for day 6 is $32.0
Your salary for day 7 is $64.0
Your salary for day 8 is $128.0
Your salary for day 9 is $256.0
Your salary for day 10 is $512.0
You have two variables with the same name and you are not using
DecimalFormat
to format the salary. You have two options to achieve what you want:Option #1
Use
DecimalFormat
to format yourdouble
:Notice that you need to use
.format()
Option #2
Use
printf()
to format your output as the following:Or use
String.format()
which will do the same thing: