ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java中的多数据类型数组

2019-08-30 13:00:09  阅读:201  来源: 互联网

标签:java arrays concatenation type-conversion


在这里完成新手的家伙.我正在研究一个Java程序来提示用户输入3个用于计算未来投资价值的变量.一切都运行得很好,除非是时候把我的数据类型放到一个数组中.

这是输出应该是什么样子:

Year        Future Value
1            $1093.80
2            $1196.41
3            $1308.65
...

这就是我的样子:

Year 1
Future Value 1093.81
Year 2
Future Value 1196.41
Year 3
Future Value 1308.65
...

我的年份是一个int值,我的Future值是一个double(四舍五入).我一直坐在这里绞尽脑汁和我能找到的所有论坛都没有成功.每次我将两个值都放入一个数组时,我得到一个关于将两个不同的数据类型放在一起的错误.任何见解将不胜感激.以下是我的完整程序的代码:

import java.util.Scanner;

class investmentValue {
    public static void main(String[] args) {
            Scanner s = new Scanner(System.in);

            System.out.print("Enter investment amount: $");
            double i = s.nextDouble();

            System.out.print("Enter percentage rate: ");
            double r = s.nextDouble()/100;

            System.out.print("Enter number of years: ");
            int y = s.nextInt();

            for (y=1; y<=30; y++) {
                double f = futureInvestmentValue(i,r,y);

                System.out.println("Year " + y);
                System.out.println("Future Value " + f);
            }
}

public static double futureInvestmentValue (double investmentAmount, double monthlyInterestRate, int years){
    double value=1;

    value = investmentAmount*Math.pow((1+(monthlyInterestRate/12)),(years * 12));
    double roundValue = Math.round(value*100.0)/100.0;

    return roundValue;

    }
}

解决方法:

一种解决方案是从实现填充功能开始.就像是,

public static String pad(String in, int len) {
    StringBuilder sb = new StringBuilder(len);
    sb.append(in);
    for (int i = in.length(); i < len; i++) {
        sb.append(' ');
    }
    return sb.toString();
}

现在我们可以将它与String.format()结合起来获得美元和美分,对标题和输出行使用一致的printf().得到类似的东西,

// Print the header.
System.out.printf("%s %s%n", pad("Year", 12), "Future Value");
for (int y = 1; y <= 30; y++) {
    String year = pad(String.valueOf(y), 13); // <-- One more in your alignment.
    String fv = String.format("$%.2f", futureInvestmentValue(i,r,y));
    System.out.printf("%s %s%n", year, fv);
}

标签:java,arrays,concatenation,type-conversion
来源: https://codeday.me/bug/20190830/1768471.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有