0

我的家庭作业有困难。我有基本的逻辑,但我搞砸了。目标是从用户输入的购物清单中制作收据。例如,用户输入:

Apples

OraNgeS // also it's not case sensitive

Oranges

Bananas

!checkout //this is to indicate the list is over

输出:

Apples x1

Oranges x2

Bananas x1

我被困住了。到目前为止我的代码:

public static void main(String[] args) {
    Scanner  keyboard    = new Scanner(System.in);

    System.out.printf("Enter the items you wish to buy:"); 
    String[] input = new String [keyboard.nextLine()];
    keyboard.nextLine(); //consuming the <enter> from input above

    for (int i = 0; i < input.length; i++) {
        input[i] = keyboard.nextLine();
    }

    System.out.printf("\nYour input:\n");
    for (String s : input) {
        System.out.println(s);
    }
}

我知道我最终必须添加 if 语句,所以如果他们输入“!checkout”,它将结束列表。但我还不能克服这个。

任何提示或建议?

4

2 回答 2

0

尝试使用ArrayList <-- 链接。

Array需要先对其进行静态初始化,然后才能使用它,而ArrayList在您为其添加值时会自动扩展。您可以使用 ArrayList 而无需在其上初始化范围。这是示例:


List<String> fruitList = new ArrayList<>();
    Scanner keyboard = null;
    Boolean isNotDone = true;
    System.out.println("Press 'Q' if you want to print out.");
    while(isNotDone) {
        keyboard = new Scanner(System.in);
        System.out.print("Input Fruits: ");
        String temp = keyboard.nextLine();
        if(temp.equalsIgnoreCase("q")) {
            isNotDone = false;
        } else {
            fruitList.add(temp);
        }
    }
    System.out.println(fruitList);
于 2016-11-11T06:27:56.403 回答
-1

以下代码将完全符合您的要求:

       Scanner keyboard = new Scanner(System.in);
       List<String> inputItems = new ArrayList<String>();       
       List<String> printedResults = new ArrayList<String>();
       String input = keyboard.nextLine();       

       while(!"!checkout".equals(input)) 
       {           
           inputItems.add(input);           
           input = keyboard.nextLine();
       }

       for(int i=0; i<inputItems.size();i++)
       {
           Integer thisItemCount = 0;
           String currentItem = inputItems.get(i);

           for(int j=0; j<inputItems.size();j++)
           {
                if(inputItems.get(j).toLowerCase().equals(currentItem.toLowerCase()))    
                    thisItemCount++;
           }

           if(!printedResults.contains(currentItem.toLowerCase()))
           {
               System.out.println(currentItem.toLowerCase() + " x" + thisItemCount);
               printedResults.add(currentItem.toLowerCase());
           }               
        }
于 2016-11-11T12:26:33.837 回答