简体   繁体   English

如何将所有用户输入存储在 do while 循环中,并在 Java 程序中稍后调用它们进行打印?

[英]How to store all the user inputs in do while loop, and call them to print later in Java program?

I have to write a Java program with do while loop.我必须编写一个带有 do while 循环的 Java 程序。 Basically it's like self-checkout register in grocery stores.基本上它就像杂货店的自助结账登记。 At first program prompts user to enter Item 1 name and price, after we enter it asks "do you want to add more?"一开始程序提示用户输入商品 1 的名称和价格,输入后它会询问“你想添加更多吗?” and prompts user.并提示用户。 if we say yes then it repeats, add Item 2 (item number increments) name and price.如果我们说是,那么它会重复,添加项目 2 (项目编号递增)名称和价格。 So it goes like this till we say "no" or till entering 10 items.如此进行直到我们说“不”或直到输入 10 个项目。 And after that program prints all item numbers correspondingly their names, and prices one by one.然后该程序将所有项目编号与其名称相对应地打印出来,并一一打印价格。 Also calculates total of all items.还计算所有项目的总数。 My code prints only last item number, name, price and total.我的代码只打印最后一个项目编号、名称、价格和总计。 I don't know how to merge array to do while.我不知道如何合并数组来做。 Example how it should look:例如它应该如何看:

_output: Enter Item1 and its price:_

_input: Tomatoes_

_input: 5.5_

_output: Add one more item?_

_input: yes_

_output: Enter Item2 and its price:_

_input: Cheese_

_input: 3.5_

_output: Add one more item?_

_input: yes_

_output: Enter Item3 and its price:_

_input: Apples_

_input: 6.3_

_output: Add one more item?_

_input: no_

_output: Item1: Tomatoes Price: 5.5, Item2: Cheese Price: 3.5, Item3: Apples Price: 6.3_

_output: Total price: 15.3_

Here's my code.这是我的代码。 It prints only last item's number, name and price with total.它仅打印最后一项的编号、名称和价格以及总计。 But can't manage to print all of them one by one as in example.但是无法像示例中那样一一打印所有内容。

        Scanner scan = new Scanner(System.in);
        
         String item;
        double price;
        int i=1;
        double total=0;
        String quest;
        String items [] = {}; 
        do {
            System.out.println("Enter item " + i + " and it's price:");
            item = scan.next();
            price=scan.nextDouble();
            i++;
            total=total+price;
           
           
           
            System.out.println("Add one more item?");
            quest=scan.next();
        } while (quest.equalsIgnoreCase("yes")) ; {
            System.out.println("Item "+i+": " + item + " Price: " + price + ",");
            System.out.println("Total price: " + total);
        }

You need to store each input in an array or collection, such as ArrayList .您需要将每个输入存储在数组或集合中,例如ArrayList

If you choose to use an array, you can ask the user how many items will be entered then use that value for the length of the array:如果您选择使用数组,您可以询问用户将输入多少项,然后使用该值作为数组的长度:

System.out.print("Enter the number of items in your cart: ");
int arraySize = scan.nextInt();

String[] itemNames = new String[arraySize];
double[] itemPrices = new double[arraySize];

If you decide you use a list, you do not need to ask the user for the list size, since lists are dynamically expanding data types:如果您决定使用列表,则无需向用户询问列表大小,因为列表是动态扩展数据类型的:

List<String> itemNames = new ArrayList<String>();
List<Double> itemPrices = new ArrayList<Double>();

Then for every iteration of your loop, you save the values into the arrays/lists:然后对于循环的每次迭代,将值保存到数组/列表中:

System.out.print("Enter the number of items in your cart: ");
int arraySize = scan.nextInt();

String[] itemNames = new String[arraySize];
double[] itemPrices = new double[arraySize];

for(int i = 0; i < ararySize; i++) {
    System.out.println("Enter item " + (i + 1) + " and it's price:");

    itemNames[i] = scan.next();
    itemPrices[i] = scan.nextDouble();

    // ...    
}
// ...

Or for the list approach:或者对于列表方法:

List<String> itemNames = new ArrayList<String>();
List<Double> itemPrices = new ArrayList<Double>();

do {
    System.out.println("Enter item " + i + " and it's price:");

    itemNames.add(scan.next());
    itemPrices.add(scan.nextDouble());

    // ...
} while (quest.equalsIgnoreCase("yes")); {
    // ...
}

Then you can iterate over the list/array to print your output:然后你可以遍历列表/数组来打印你的输出:

for(int i = 0; i < itemNames.length; i++) {
    String name = itemNames[i];
    double price = itemPrices[i];
    System.out.println("Item " + i + ": " + name + " Price: " + price + ",");
}

For list:对于列表:

for(int i = 0; i < itemNames.size(); i++) {
    String name = itemNames.get(i);
    double price = itemPrices.get(i);
    System.out.println("Item " + i + ": " + name + " Price: " + price + ",");
}

I finally solved the task.我终于解决了这个任务。 Thanks everybody who helped, really appreciated.感谢所有帮助过的人,真的很感激。 Here's the code:这是代码:

  Scanner scan = new Scanner(System.in);
  String itemName;
  double price;
  String [] items = new String [10] ;
  double [] prices = new double [10];
  int itemNumbers[]=new int [10];
  String answer;
  double total=0;
  int i=1;
  
  int index=0;
  do {
      System.out.println("Enter item " + i + " and it's price:");
      itemName=scan.next();
      price=scan.nextDouble();
      scan.nextLine();
      total=total+price;
      items[index]=itemName;
      prices[index]=price;
      itemNumbers[index]=i;
      index++;
      System.out.println("Add one more item?");
      answer=scan.next();
      i++;
      
  } while (answer.equalsIgnoreCase("yes") && i<=10) ; {
      for (int j=0; j<index; j++) {
          System.out.print("Item "+ itemNumbers[j] +": " + items[j] + " price: " + prices[j] + ",");
      }
  }
      System.out.println("\nTotal price: " + total);
}

} }

This version works too. Without arrays.

String shoppingList = "";
            String item = "";
            String addMore = "";
            double price = 0;
            int count = 1;
            double totalPrice = 0;

            do {
                System.out.println("Enter Item"+ count + " and its price:");
                item = scan.next();
                price = scan.nextDouble();
                shoppingList += ("Item" + count + ": " + item + " Price: " + price + ", ");
                totalPrice += price;
                System.out.println("Add one more item?");
                addMore = scan.next();
                count++;
            } while (addMore.equalsIgnoreCase("yes"));
            System.out.println(shoppingList.substring(0, shoppingList.length()-2));
            System.out.println("Total price: " + totalPrice);
        

暂无
暂无

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

相关问题 如何在 while 循环中获取所有用户输入并将它们放入打印语句中 - How do I take all of the user inputs in a while loop and put them into a print statement 如何在循环中捕获重复出现的用户输入,然后在程序结束时全部显示它们? - How can I capture recurring user inputs in a loop and then display them all at the end of the program? 如何将单个输入保存在while循环中并在最后打印出来? - How do i save individual inputs in a while loop and print them at the end? 如何在Java中输入(除非用户输入0以终止程序)? - How do I get while input (except when the user inputs 0 that terminates the program) in Java? 如何在java中存储对象并在以后检索它们? - How to store objects and retrieve them later in java? 如何让我的程序从 do while 循环中打印出我的所有输入? - How do I get my program to print out all of my input from a do while loop? 如何在 java 中创建一个 while 循环,一旦两个用户输入匹配就会结束游戏? - How do I create a while loop in java that will end the game once the two user inputs match? 如何拍摄用户图像,存储它们,并在以后渲染它们? - How to take user images, store them, and render them later? 如何将对象类型的数组存储为字符串,以便另一个类以后可以调用并打印该字符串。 爪哇 - How to store an array of object types as a string so another class can later call and print that string. java 如何打印循环中使用的所有输入 - How to print all inputs used from loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM