java - 如何在 Java 中将值存储在不同的数组中?
问题描述
我想将非“h”值存储在数组中。所以为了给你一个背景知识,我需要制作一个基本的收银机,它可以接受 5 个数组中的物品,上面有价格。不过,有些商品将包含 HST(税)。了解哪些项目有税哪些没有。用户将在输入美元金额之前或之后按 h 或 H。我已将带有 HST 的值存储在一个数组中,但我将如何存储非 HST 值?
注意:我尝试将其与我的“h”值相同,但它不起作用,这就是我感到困惑的原因
我不能使用 Arrayslist 或任何其他数组方法
样本输入:
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]);
}
}
}
解决方案
您可以首先选择具有 "H" 或 "h" 的输入contains。
然后您可以使用replaceAll将“h”或“h”替换为空字符串“”。您可以使用正则表达式“[hH]”来定位大写和小写。您可以在此处查看如何为正则表达式定义一组字符。
推荐阅读
- python - 有没有 dict + list 理解方式来做到这一点?
- javascript - 在 Google 表格中编辑历史记录
- python - 将 CSV 转换为分层 JSON 输出
- javascript - 如何从 Angular 6 中的选定下拉列表将 Id 传递给我的 API 请求?
- regex - 为什么匹配运算符的“仅匹配一次”优化仅适用于“?” 分隔符?
- c# - 存储的一半在unity build中填充在哪里?
- android - Kotlin 枚举到基本类型的映射
- java - JD GUI反编译器无法通过Mac上拖放以外的任何其他文件打开方法工作
- javascript - 如何匹配小写字母和选择的标点符号?
- java - Java中是否有一个关键字is,类似于Python的“is”?