在Java中如何将值存储在不同的数组中?
我想在数组中存储非“h”值。所以为了给你们一个背景,我需要做一个基本的收银机,它可以接受5个项目,每个项目都有一个价格。然而,有些项目将包含HST(税)。了解哪些项目有税,哪些没有税。用户将在输入美元金额之前或之后按h或h。我已经将HST的值存储在一个数组中,但是如何存储非HST的值呢 注意:我试着按照我的“h”值来做,但它不起作用,这就是我感到困惑的原因 我不能使用Arrayslist或任何其他数组方法 样本输入:在Java中如何将值存储在不同的数组中?,java,arrays,Java,Arrays,我想在数组中存储非“h”值。所以为了给你们一个背景,我需要做一个基本的收银机,它可以接受5个项目,每个项目都有一个价格。然而,有些项目将包含HST(税)。了解哪些项目有税,哪些没有税。用户将在输入美元金额之前或之后按h或h。我已经将HST的值存储在一个数组中,但是如何存储非HST的值呢 注意:我试着按照我的“h”值来做,但它不起作用,这就是我感到困惑的原因 我不能使用Arrayslist或任何其他数组方法 样本输入: 4.565H H2.3435 4.565h 5.234 5.6576h 样本
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]);
}
}
}
import java.util.Scanner;
班长{
公共静态void main(字符串[]args){
//创建扫描仪对象并设置扫描仪变量
扫描仪inp=新扫描仪(System.in);
System.out.println(“按任意键启动”);
String key=inp.nextLine();
System.out.println(“\n输入每个项目的金额”);
System.out.println(“最多允许5个输入!\n”);
//初始化计数器和索引变量以在while循环中使用它
int计数器=0;
int指数=0;
//创建一个双数组变量,并将限制设置为5
double[]数字=新的double[5];
//创建一个布尔变量以在while循环中使用它
布尔go=true;
while(go){
字符串值=inp.nextLine();
value=value.toLowerCase();
//将索引值设置为“h”或“h”
int indexOfh=value.indexOf('h');
布尔containsh=(indexOfh==0 | | indexOfh==value.length()-1);
如果(containsh){//在开始或结束时验证h
numbers[index]=Double.parseDouble(value.replace(“h”)和“);
索引++;
System.out.println(“该值将考虑HST”);
}
计数器++;
如果(计数器==5){
go=假;
}
}
System.out.println(“HST值:”);
for(int i=0;i
您可以首先选择带有“H”或“H”的输入
然后可以使用将“h”或“h”替换为空字符串“”。您可以使用正则表达式“[hH]”以大写和小写为目标。您可以了解如何为正则表达式定义一组字符