首页 > 解决方案 > 如何在 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]);
        }
    }
}

标签: javaarrays

解决方案


您可以首先选择具有 "H" 或 "h" 的输入contains

然后您可以使用replaceAll将“h”或“h”替换为空字符串“”。您可以使用正则表达式“[hH]”来定位大写和小写。您可以在此处查看如何为正则表达式定义一组字符。


推荐阅读