Lucas Matheus Lucas Matheus - 22 days ago 9
Java Question

Ask user to choose from array

I'm practicing Java and wanted to let the user choose an option from the Array such as:

String Food[] = {"Beans","Rice","Spaghetti"};


So far I only know of Scanner, but this is my first program so I don't know much of the subject.

Also, is there a way to print it? besides doing:

System.out.println(Food[0]); //and so on


for every single one of them.

Edit: not a Array list.

Answer

You can print the Array not ArrayList by doing:

System.out.println(Arrays.toString(Food));

It will print out: [Beans, Rice, Spaghetti]

If you are talking about an ArrayList, you would have to do:

ArrayList<String> Food = new ArrayList<String>();

Food.add("Beans");
Food.add("Rice");
Food.add("Spaghetti");

Then, you can loop over the ArrayList and build your own String with a StringBuilder

After reading your comment, I think you have a problem structuring your program. I will help you with that. Basically you have to complete these steps:

  1. Program starts
  2. Program outputs the options available in the menu
  3. Program asks the user to choose one of the listed options
  4. User chooses an option
  5. Program will repeat step 3, only if the user wants to keep adding stuff to his order.
  6. If the user does not want anything else, the Program outputs the total cost of the order

Some ideas of how to achieve this the right way:

  1. I would use a class to encapsulate the characteristics of an "order". For instance: description, name, and price are important stuff that you need to be able to track per item.

  2. when you don't know how many times your program will run, you have two options: using a do while loop or a while loop. Try to think in a condition that could make your program run indefinitely a number of times until the user is done. Inside the loop, you could have a sum variable where you would keep track of the items that the user wants.

  3. It is better to keep track of items by just using numbers than Strings. Computers are faster to find stuff this way. So, if you use a HashMap to mock a database system in your program, it would make it better and faster. Then, instead of using if else to control your flow, you could use a switch instead.

I hope this helps.

Comments