将多个字符串添加到数组中

时间:2016-11-11 05:54:33

标签: java arrays string for-loop toupper

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

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”它将结束列表。但我还没有过去。

任何提示或建议?

2 个答案:

答案 0 :(得分:0)

尝试使用ArrayList&lt; - Link。

数组需要先进行静态初始化才能使用它,而 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);

答案 1 :(得分:-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());
           }               
        }