首页 > 解决方案 > 将货币表从 USD 输出到 CNY

问题描述

我的教育任务是:“让程序输出一张关于以当前汇率将 1,2, ...20 USD 转换为 CNY 的表格(从键盘输入)”

我可以做这样的事情:

public class TaskCurremcy {
public static void main(String[] args) {
    System.out.println("Enter current exchange rate:");
    Scanner sc = new Scanner(System.in);
    int value = sc.nextInt();
    System.out.println(Arrays.toString(convertDollarArray(value)));
}

public static int[] convertDollarArray(int n) {
    int [] currencyArray = new int[21];
    int [] convertedValue = new int[21];
    for (int i = 1; i < currencyArray.length; i++) {
        currencyArray[i] = i;
        convertedValue[i] = currencyArray[i] * n;
    }
    return convertedValue;
  }
}

但是如果我从键盘输入“6”,我会得到这个输出:[0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96, 102, 108, 114, 120]

如何像工作表一样以垂直方式显示它以及如何跳过“0”并从数组的“1”位置开始?感谢您的关注!

标签: javaarrays

解决方案


您可以考虑添加一个实用方法来打印结果,并接受要跳过的索引作为参数。最后的方法是一个例子。

public class TaskCurrency {

    public static void main(String[] args) {
        System.out.println("Enter current exchange rate:");
        Scanner sc = new Scanner(System.in);
        int value = sc.nextInt();
        printVertical(convertDollarArray(value), 0);
    }

    public static int[] convertDollarArray(int n) {
        int[] currencyArray = new int[21];
        int[] convertedValue = new int[21];
        for (int i = 1; i < currencyArray.length; i++) {
            currencyArray[i] = i;
            convertedValue[i] = currencyArray[i] * n;
        }
        return convertedValue;
    }

    // New method to print while skipping
    public static void printVertical(int[] arr, int skipIndex) {
        for (int i = 0; i < arr.length; i++)
            if (i == skipIndex) { // Skip the index you want
            } else
                System.out.println(arr[i]); // Or else print the result in a new array
    }

}

推荐阅读