java - 我如何将值存储在java中的数组中?
问题描述
我想将非“h”值存储在数组中。所以为了给你一个背景知识,我需要制作一个基本的收银机,它可以接受 5 个数组中的物品,上面有价格。不过,有些商品将包含 HST(税)。了解哪些项目有税哪些没有。用户将在输入美元金额之前或之后按 h 或 H。我已将带有 HST 的值存储在一个数组中,但我将如何存储非 HST 值?
样本输入:
4.565H
H2.3435
4.565h
5.234
5.6576h
样本输出:
HST Values:
4.565
2.3435
4.565
5.6576
Non-HST Values
5.234
我的代码:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// Create scanner object and set scanner variables
Scanner inp = new Scanner(System.in);
System.out.println("Press any key to start");
String key = inp.nextLine();
System.out.println("\nEnter the amount of each item");
System.out.println("Up to 5 inputs are allowed!\n");
// Initialize counter and index variables to use it in the while loop
int counter = 0;
int index = 0;
// Create a double array variable, and set the limit to 5
double[] numbers = new double[5];
// Create a boolean variable to use it in the while loop
boolean go = true;
while (go) {
String value = inp.nextLine();
value = value.toLowerCase();
// Set the index value to "h" or "H"
int indexOfh = value.indexOf('h');
boolean containsh = (indexOfh == 0 || indexOfh == value.length() - 1);
if (containsh) { //Validate h at beginning or end
numbers[index] = Double.parseDouble(value.replace("h", ""));
index++;
System.out.println("HST will be taken account for this value");
}
counter++;
if (counter == 5) {
go = false;
}
}
System.out.println("HST Values:");
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
解决方案
我建议您ArrayList
改用:
import java.util.ArrayList;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// Create scanner object and set scanner variables
Scanner inp = new Scanner(System.in);
System.out.println("Press any key to start");
String key = inp.nextLine();
System.out.println("\nEnter the amount of each item");
System.out.println("Up to 5 inputs are allowed!\n");
// Initialize counter and index variables to use it in the while loop
int counter = 0;
// Create a double array variable, and set the limit to 5
ArrayList<Double> numbers = new ArrayList<Double>();
// Create a boolean variable to use it in the while loop
boolean go = true;
while (go) {
String value = inp.nextLine().toLowerCase();
int indexOfH = value.indexOf('h');
if (indexOfH == 0 || indexOfH == value.length() - 1) { //Validate h at beginning or end
numbers.add(Double.parseDouble(value.replace("h", "")));
System.out.println("HST will be taken account for this value");
}
counter++;
if (counter == 5)
go = false;
}
System.out.println("HST Values:");
System.out.println(numbers);
}
}
推荐阅读
- jquery - 在 daterangepicker 中获取数据
- ibm-cloud - 有没有办法在不调用 assistant.message 的情况下设置上下文变量?
- flutter - 使用 CustomPainter 时小部件的涂抹
- php - 使用 ajax 时表函数不起作用
- react-native - 升级我的依赖项后,我无法使用命令“npx react-native run-android”在模拟器上构建 android
- java - 递归函数如何在内部工作
- laravel - HTML2Canvas 截图分区
- php - 如何“展平”未知深度和长度的多维数组并记录它的父子关系?
- batch-file - Windows 7批量增加循环中的变量不起作用
- javascript - 路由器模板中的 Vue 计算属性