[英]How would I store values in an array in 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);
}
}
您只需要两个数组,一个用于 H 值,另一个用于非 H。为什么不使用列表? 列表会更好
但是,如果要求是数组,则只需通过检查“H”值来存储 h 值,如果“H”的索引为 -1,则表示该值不包含 h,则只需将这些值添加到另一个数组中并在最后打印出来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.