[英]using the NumberFormat import in System.out.format
I'm doing a program on compound interest for a school assignment. 我正在为一个学校作业做一个复利计划。 I tried using System.out.format(); 我尝试使用System.out.format(); and used money.format to format the variables investment, interest, and investTotal. 并使用money.format格式化变量投资,利息和investedTotal。 I don't know why but it keeps on throwing me an error for "Invalid value type 'String' for format specifier '%.2f', parameter 2, 3, and 4" I've been trying to figure this out for quite a while now and I still can't seem to find why it is. 我不知道为什么,但是它一直在向我抛出“格式说明符'%.2f',参数2、3和4的无效值类型'String'的错误”,我一直在设法解决这个问题过了一会儿,我似乎仍然找不到原因。
-- A - 一种
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// SPLASH
// CONSTANT
// OBJECT
Scanner input = new Scanner(System.in);
NumberFormat money = NumberFormat.getCurrencyInstance();
// VARIABLES
double investment;
double investTotal;
double rate;
double intrest;
int year;
// INPUT
do
{
System.out.print("Enter yearly investment (min $100.00 deposit): ");
investment = input.nextDouble();
}
while (investment < 100);
do
{
System.out.print("Enter intrest rate (%): ");
rate = input.nextDouble()/100;
}
while (rate <= 0);
do
{
System.out.print("Enter number of years: ");
year = input.nextInt();
}
while (year <= 0 || year > 15);
// PROCESSING
investTotal = investment;
for (int perYear = 1; perYear <= year; perYear++)
{
intrest = investTotal*rate;
investTotal = (investment+intrest);
System.out.format("%2s | %.2f | %.2f | %.2f\n", perYear, money.format(investment), money.format(intrest), money.format(investTotal));
investTotal = investTotal + investment;
}
// OUTPUT
}
} }
getCurrencyInstance returns a String and therefor can't be formatted using %.2f. getCurrencyInstance返回一个字符串,因此无法使用%.2f进行格式化。
You better look how NumberFormat works: https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html 您最好看一下NumberFormat的工作方式: https : //docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
As you can see, the result of the formatting is a String, when you are using String.format with %.2f you should enter a number eg: System.out.format("%2s | %.2f\\n", 1.001, 1.005); 如您所见,格式化的结果是一个字符串,当您将String.format与%.2f一起使用时,应输入一个数字,例如:System.out.format(“%2s |%.2f \\ n”,1.001 ,1.005);
I'm not sure what are you trying to get using the NumberFormat, if you classify I will be able to help you further with this question. 我不确定您要使用NumberFormat尝试什么,如果您进行分类,我将能够进一步帮助您解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.