Corey Dean Corey Dean - 28 days ago 9
Java Question

Getting multiple Strings into an Array

I'm having difficulties with my homework. I have the basic logic down but I'm messing up. The objective is to make a receipt from a shopping list that's inputted by the user. For example, the user enters:

Apples

OraNgeS // also it's not case sensitive

Oranges

Bananas

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


Output:

Apples x1

Oranges x2

Bananas x1


I'm stuck. My code so far:

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);
}
}


I know I'll have to add the if statement eventually so if they type in "!checkout" it'll end the list. but I can't get past this yet.

Any tips or advice?

Answer

This code will do exactly what you are looking for:

       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());
           }               
        }