java - 将货币表从 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”位置开始?感谢您的关注!
解决方案
您可以考虑添加一个实用方法来打印结果,并接受要跳过的索引作为参数。最后的方法是一个例子。
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
}
}
推荐阅读
- amazon-redshift - 与 Redshift 原生表和外部表联合 (Spectrum)
- reactjs - React Redux 错误页面在获取数据之前显示
- python - 如何使用 Python 中的响应来模拟(相同的请求但不同的答案)请求?
- java - 如何在内部保持 hashmap 中键的唯一性
- python - 多索引数据框导致绘制数据之间的广泛分离
- javascript - 如何加载最后包含 #tags=green,pink,white 的 URL 页面
- javascript - availableQuestions 返回长度:函数内的 0(测验应用程序)
- typescript - VsCode API:在没有命令的情况下运行扩展?
- python - 如何将前四位数字添加到另一个列表中
- assembly - 使用宏在 MASM 中除数?