简体   繁体   English

将数据插入未知长度数组java

[英]Inserting data into unknown length array java

I am making a program for a receipt maker and the array length is unknown due to multiple items.我正在为收据制作者制作一个程序,由于多个项目,数组长度未知。 This is the code I have:这是我的代码:

public static void main (String str[]) throws IOException {
    Scanner scan = new Scanner (System.in);
    //Entering Input
    int mult = 1;
    double price = 0;
    double y = 0;
    int l = 1;
    double [] list = new double[l];
    while(mult != 0){
      if (mult != 0)
        System.out.println("Please Enter the Cost of the Item: ");
        y = scan.nextDouble();
        list[l]= y;
        l++;
      System.out.println("More than one item? (1 = yes 0 = no) ");
      mult = scan.nextInt();
      if (mult != 0)
        price += y;
    }

and when I run it I enter the cost of the item and get an error.当我运行它时,我输入了该项目的成本并出现错误。

If I were you, I would use an array list.如果我是你,我会使用数组列表。 It is a dynamic data structure that you can use, rather than a typical array where you have to define the number of elements.它是您可以使用的动态数据结构,而不是您必须定义元素数量的典型数组。 You can do something like:您可以执行以下操作:

ArrayList<Double list = new ArrayList<Double>();
list.add(y); 

Then you get elements by doing list.get(1) or what ever element you want.然后你通过执行list.get(1)或任何你想要的元素来获取元素。

Doing something like this will prevent you from having to know exactly how many elements you need when you declare your array.这样做可以防止您在声明数组时确切知道需要多少个元素。

There is no such thing as an unknown length array.没有未知长度数组这样的东西。 Anything that is an array (of any type) in Java has a field length . Java 中的任何数组(任何类型)都有一个字段length

But actually that isn't your problem;但实际上这不是你的问题; as you are not using that array that is passed to your method at all.因为您根本没有使用传递给您的方法的数组。 In essence you are asking how to use arrays for an unknown size of input.本质上,您是在询问如何将数组用于未知大小的输入。

There are two answers:有两个答案:

  1. As BlackHatSamurei suggests, you use List<Double> numbers = new ArrayList<>() - existing classes that grow dynamically when adding additional elements [ where you use List all the time, and only when instantiating the concrete object you use the specific ArrayList implemenation ]正如 BlackHatSamurei 建议的那样,您使用List<Double> numbers = new ArrayList<>() - 在添加其他元素时动态增长的现有类 [ 您一直使用List ,并且仅在实例化您使用特定 ArrayList 实现的具体对象时]
  2. If this is about learning: you implement your own version of List.如果这是关于学习:您实现自己的 List 版本。 Meaning: you create a class that uses an array to store data, and whenever you want to add more elements that your array can hold;含义:您创建了一个使用数组存储数据的类,并且每当您想添加数组可以容纳的更多元素时; you create a new, larger array and copy all data into that array.您创建一个新的更大的数组并将所有数据复制到该数组中。

ArrayList

As the others suggested, you should use a Collection , specifically a List , more specifically an ArrayList .正如其他人所建议的,您应该使用Collection ,特别是List ,更具体地说是ArrayList

A plain array is of fixed length.普通数组是固定长度的。 It does not grow or shrink.它不会增长或缩小。 To add items beyond its capacity, you create a new bigger array and copy over existing items plus the new item, finally deleting the original array.要添加超出其容量的项目,您可以创建一个更大的数组并复制现有项目和新项目,最后删除原始数组。 An ArrayList is backed by an array but can grow. ArrayList由数组支持,但可以增长。 Actually, the backing array does not actually grow, it handles the details I just mentioned on your behalf: monitors the array to detect when full, then creates a new array, copies items over.实际上,后备数组实际上并没有增长,它处理我刚才代表您提到的细节:监视数组以检测何时已满,然后创建一个新数组,复制项目。

If this is homework, your instructor may be expecting you to learn the details of this chore, in which case I gave you that answer to: Create a new array, copy items, add new item, replace original array.如果这是家庭作业,您的教师可能希望您了解这项杂务的详细信息,在这种情况下,我给您的答案是:创建新数组、复制项目、添加新项目、替换原始数组。

To use a Collection (see Tutorial ), you need to progress past working with just primitives and use actual objects.要使用Collection (请参阅 教程),您需要超越仅使用基元并使用实际对象。 Java has primitives to help programmers transitioning from C programming, but classes and objects is really what Java is about. Java 具有帮助程序员从 C 编程过渡的原语,但类和对象才是 Java 真正的意义所在。 The class equivalent to double primitive is Double .等效于double原语的类是Double

List<Double> costs = new ArrayList<>();
// … get your inputs from user and add each price-item to list …
costs.add ( y );

Simplify your logic简化你的逻辑

Also, your logic is convoluted, such as defining l but never using it.此外,您的逻辑很复杂,例如定义了l但从不使用它。 I tried rewriting your code but gave up.我尝试重写您的代码但放弃了。 I suggest you try smaller bites, getting one thing to work at a time, building up to your desired app.我建议你尝试小一点,一次做一件事,构建你想要的应用程序。 Get data-entry working for a single price item, then after that works try supporting multiple price items.获取针对单个价格项目的数据输入,然后在该工作之后尝试支持多个价格项目。 That is how real programming work is done, one small piece at a time.真正的编程工作就是这样完成的,一次一小块。

Tip: Use descriptive names on your variables.提示:对变量使用描述性名称。 That will help clarify your thinking.这将有助于澄清你的想法。

BigDecimal

Also, in the real world you would never use double or Double for prices or anything related to money.此外,在现实世界中,您永远不会将doubleDouble用于价格或与金钱相关的任何事情。 Both of those data types use floating-point technology which trades away accuracy for speed-of-execution.这两种数据类型都使用浮点技术,以牺牲准确性换取执行速度。 So the results are approximate, not exact, and often have extraneous digits in the far right of the decimal fraction.所以结果是近似的,而不是精确的,并且在小数部分的最右边经常有多余的数字。

For money and other areas where accuracy matters, use BigDecimal objects.对于货币和其他精度很重要的领域,请使用BigDecimal对象。 Feed BigDecimal a string, not a double-value as you might have already introduced the dreaded extraneous digits.BigDecimal一个字符串,而不是一个双值,因为您可能已经引入了可怕的无关数字。 This area is another reason to learn to use objects rather than primitives.这个区域是学习使用对象而不是基元的另一个原因。

List<BigDecimal> costs = new ArrayList<>();
…
BigDecimal bd = new BigDecimal( userInputString ) ; // Input might be: 1.23
costs.add( bd );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM