如何使用 replace 方法将值存储在新数组中?

huangapple go评论72阅读模式
英文:

How to store values in a new array by using replace method?

问题

我想在数组中存储非 "h" 值。所以为了给你提供背景,我需要制作一个基本的现金注册器,它接受一个包含价格的数组中的5个项目。然而,一些项目将包括HST(税)。为了知道哪些项目有税,哪些没有。用户将在输入金额之前或之后按下 "h" 或 "H"。我已经将带有HST的值存储在数组中,但是如何存储非HST的值呢?

注意:我尝试过像处理我的 "h" 值一样处理它们,但是不起作用,所以我很困惑。

我不能使用Arrayslist或任何其他数组方法

示例输入:

4.565H
H2.3435
4.565h
5.234
5.6576h

示例输出:

HST 值:
4.565
2.3435
4.565
5.6576

非 HST 值:
5.234


这是我尝试过的,但不起作用:

// 导入扫描器类
import java.util.Scanner;

// 创建类和方法
class Main {
  public static void main(String[] args) {

    // 创建扫描器对象并设置扫描器变量
    Scanner inp = new Scanner(System.in);
    System.out.println("按任意键开始");
    String key = inp.nextLine();
    System.out.println("\n输入每个项目的金额");
    System.out.println("最多允许输入5个!\n");

    // 初始化计数器和索引变量以在while循环中使用
    int counter = 0;
    int index = 0;
    int index2 = 0;

    // 创建一个双精度数组变量,并将限制设置为5
    Double[] numbers = new Double[5];
    Double[] numbers2 = new Double[5];

    // 创建一个布尔变量以在while循环中使用
    boolean go = true;

    while (go) {
      String value = inp.nextLine();
      value = value.toLowerCase();

      // 设置索引值为 "h" 或 "H"
      int indexOfh = value.indexOf('h');

      boolean containsh = indexOfh == 0 || indexOfh == (value.length() - 1);

      if (containsh) { // 验证是否以"h"开头或结尾
        numbers[index] = Double.parseDouble(value.replace("h", ""));
        index++;
        System.out.println("此值将考虑HST");
      } else {
        numbers2[index2] = Double.parseDouble(value.replace("", "")); // value.replace 是一个问题
      }
      counter++;
      if (counter == 5) {
        go = false;
      }
    }
    System.out.println("\nHST 值:");

    for (int i = 0; i < numbers.length; i++) {

      // 如果值缺失,打印HST值
      if (numbers[i] != null) {
        System.out.println(numbers[i]);
      }
    }
    System.out.println("\n非 HST 值:");
    for (int x = 0; x < numbers2.length; x++) {
      if (numbers2[x] != null) {
        System.out.println(numbers2[x]);
      }
    }
  }
}
英文:

I want to store non "h" values in an array. So to give you a background, I need to make a basic cash register that accepts 5 items in an array with a price on them. Nevertheless, some items will have HST(tax) included with them. To know which items have tax and which don't. The user will press h or H before or after entering the dollar amount. I have stored the values with the HST in an array, but how would I store the non-HST values?

NOTE: I tried doing it as the same as my "h" values, but it would not work that's why I am confused

I cannot use Arrayslist or any other array methods

Sample input:

4.565H
H2.3435
4.565h
5.234
5.6576h

Sample Output:

HST Values:
4.565
2.3435
4.565
5.6576
Non-HST Values
5.234

This is What I tried But it won't work:

  // Import scanner class
import java.util.Scanner;
// Create class and method
class Main {
public static void main(String[] args) {
// Create scanner object and set scanner variables
Scanner inp = new Scanner(System.in);
System.out.println(&quot;Press any key to start&quot;);
String key = inp.nextLine();
System.out.println(&quot;\nEnter the amount of each item&quot;);
System.out.println(&quot;Upto 5 inputs are allowed!\n&quot;);
// Initialize counter and index variables to use it in the while loop
int counter = 0;
int index = 0;
int index2 = 0;
// Create a double array variable, and set the limit to 5
Double[] numbers = new Double[5];
Double[] numbers2 = 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 &quot;h&quot; or &quot;H&quot;
int indexOfh = value.indexOf(&#39;h&#39;);
boolean containsh = indexOfh == 0 || indexOfh == (value.length() - 1);
if (containsh) { // Validate h at beginning or end
numbers[index] = Double.parseDouble(value.replace(&quot;h&quot;, &quot;&quot;));
index++;
System.out.println(&quot;HST will be taken account for this value&quot;);
}else{
numbers2[index2] = Double.parseDouble(value.replace(&quot;&quot;,&quot;&quot;)); // value.replace is an issue
}
counter++;
if (counter == 5) {
go = false;
}
}
System.out.println(&quot;\nHST Values:&quot;);
for (int i = 0; i &lt; numbers.length; i++) {
// If there is any absence of values, print the HST values
if (numbers[i] != null) {
System.out.println(numbers[i]);
}
}
System.out.println(&quot;\nNon-HST Values:&quot;);
for (int x = 0; x &lt; numbers2.length; x++){
if (numbers2[x] != null){
System.out.println(numbers2[x]);
}
}
}
}

答案1

得分: 1

试一下这个:

我更改的部分:

1)numbers2[index2] = Double.parseDouble(value); // 这里不需要做任何替换

2)index2++ ,我注意到你在增加 index,但是没有增加 index2

3)当你打印 HST 和非-HST 值时,你不需要遍历到 numbers.length 或者 numbers2.length,因为你知道 indexindex2 的值,你已经知道每个数组中的值。

如果你按照这种方式做,那么在打印时就不需要进行空值检查。

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {

        // 创建扫描器对象并设置扫描器变量
        Scanner inp = new Scanner(System.in);
        System.out.println("按任意键开始");
        String key = inp.nextLine();
        System.out.println("\n输入每个项目的金额");
        System.out.println("最多允许输入 5 个!\n");

        int counter = 0;
        int index = 0;
        int index2 = 0;

        Double[] numbers = new Double[5];
        Double[] numbers2 = new Double[5];

        boolean go = true;

        while (go) {
            String value = inp.nextLine();
            value = value.toLowerCase();

            // 将索引值设置为 "h" 或 "H"
            int indexOfh = value.indexOf('h');

            boolean containsh = indexOfh == 0 || indexOfh == (value.length() - 1);

            if (containsh) { // 验证是否以 h 开头或结尾
                numbers[index] = Double.parseDouble(value.replace("h", ""));
                index++;
                System.out.println("此值将计入 HST");
            } else {
                numbers2[index2] = Double.parseDouble(value); // 在这里进行了更改
                index2++; // 添加了这一行
            }
            counter++;
            if (counter == 5) {
                go = false;
            }
        }
        System.out.println("\nHST 值:");

        for (int i = 0; i < index; i++) { // 在这里进行了更改

            // 现在不需要进行空值检查
            System.out.println(numbers[i]);

        }
        System.out.println("\n非-HST 值:");
        for (int x = 0; x < index2; x++) { // 在这里进行了更改
            // 现在不需要进行空值检查
            System.out.println(numbers2[x]);

        }
    }
}
英文:

Try this:

Things I changed:

  1. numbers2[index2] = Double.parseDouble(value); // no need to replace anything here

  2. index2++ , I see you increment index but not index2

  3. When you print HST and non-HST value, you do not need to go till numbers.length or numbers2.length, because you know the values of index and index2, you already know the values in each array.

If you do this way then you do not need to do null check when you are printing.

    import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create scanner object and set scanner variables
Scanner inp = new Scanner(System.in);
System.out.println(&quot;Press any key to start&quot;);
String key = inp.nextLine();
System.out.println(&quot;\nEnter the amount of each item&quot;);
System.out.println(&quot;Upto 5 inputs are allowed!\n&quot;);
int counter = 0;
int index = 0;
int index2 = 0;
Double[] numbers = new Double[5];
Double[] numbers2 = new Double[5];
boolean go = true;
while (go) {
String value = inp.nextLine();
value = value.toLowerCase();
// Set the index value to &quot;h&quot; or &quot;H&quot;
int indexOfh = value.indexOf(&#39;h&#39;);
boolean containsh = indexOfh == 0 || indexOfh == (value.length() - 1);
if (containsh) { // Validate h at beginning or end
numbers[index] = Double.parseDouble(value.replace(&quot;h&quot;, &quot;&quot;));
index++;
System.out.println(&quot;HST will be taken account for this value&quot;);
} else {
numbers2[index2] = Double.parseDouble(value); // changed here
index2++; //added this line
}
counter++;
if (counter == 5) {
go = false;
}
}
System.out.println(&quot;\nHST Values:&quot;);
for (int i = 0; i &lt; index; i++) { // changed here
// no need to do null check now
System.out.println(numbers[i]);
}
System.out.println(&quot;\nNon-HST Values:&quot;);
for (int x = 0; x &lt; index2; x++) { // changed here
// no need to do null check now
System.out.println(numbers2[x]);
}
} } 

答案2

得分: 0

无法返回完整的翻译,因为您的代码部分包含了许多技术性的术语和特定编程语言的元素,需要一定的上下文才能正确地翻译。如果您有特定的翻译需求,可以提供一些具体的指示,我会根据您的指示进行翻译。

英文:

The issue with the failed parsing of non-HST values is generally resolved in @Anon's answer above, however there are some other points to make code cleaner:

  • provide a constant instead of hardcoded length of arrays 5
  • remove redundant messages
  • improve logic, rename variables and remove redundant ones
  • improve handling of errors in user's input
  • use String matches method with a case-insensitive regexp to check if the item is HST or not
public static void main(String[] args) {
    
    final int SIZE = 5;
    
    // Create a double array variable, and set the limit
    double[] hstItems = new double[SIZE];
    double[] nonHstItems = new double[SIZE];

    // Create scanner object and set scanner variables
    Scanner inp = new Scanner(System.in);
 
    System.out.printf(&quot;Enter up to %d HST or non-HST items%n&quot;, SIZE);

    // Initialize counter and index variables to use it in the while loop
    int counter = 0;
    int hstCount = 0;
    int nonHstCount = 0;

    while (counter++ &lt; SIZE) {
        String value = inp.nextLine();
        try {
            if (value.matches(&quot;(?i)(h.+|.+h)&quot;)) {
                hstItems[hstCount++] = Double.parseDouble(value.replaceAll(&quot;(?i)h&quot;, &quot;&quot;));
                System.out.println(&quot;HST will be taken into account for this value&quot;);
            } else {
                nonHstItems[nonHstCount++] = Double.parseDouble(value);
                System.out.println(&quot;No HST is taken into account for this value&quot;);
            }
        } catch (Exception ex) {
            System.out.printf(&quot;Failed to parse value: %s, error: %s, please try again%n&quot;, value, ex.getMessage());
            counter--;
        }
    }

    System.out.println(&quot;\nHST Values:&quot;);
    for (int i = 0; i &lt; hstCount; i++) {
        System.out.println(hstItems[i]);
    }

    System.out.println(&quot;\nNon-HST Values:&quot;);
    for (int i = 0; i &lt; nonHstCount; i++) {
        System.out.println(nonHstItems[i]);
    }
}

huangapple
  • 本文由 发表于 2020年10月11日 00:01:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/64295455.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定