Ask user to choose from array - java

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.

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:
Program starts
Program outputs the options available in the menu
Program asks the user to choose one of the listed options
User chooses an option
Program will repeat step 3, only if the user wants to keep adding stuff to his order.
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:
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.
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.
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.

EDIT: For a more efficient way of printing out the contents of the array, use an enhanced for-loop:
for(String f : Food)
{
System.out.println(f);
}
This is effectively the same as:
for(int i = 0; i < Food.size(); i++)
{
System.out.println(Food[i])
}
If I'm understanding what you're trying to do correctly, I think this should suffice (disclaimer, it's been a while since I've worked with Scanner():
public static void main(String[] args)
{
String[] food = {"Beans","Rice","Spaghetti"}; // Java standards are lowercase for variables and objects, uppercase for class names.
Scanner in = new Scanner(System.in);
System.out.println("What would you like to eat? Options:");
for(String f : food)
{
System.out.println(f);
}
String response = in.next();
boolean validEntry = false;
for(String f: food)
{
if(response.equalsIgnoreCase(f))
{
validEntry = true;
}
}
if(validEntry)
{
System.out.println("You chose " + response);
}
else
{
System.out.println("Invalid entry. Please retry.")
}
}

Related

Insert ArrayList into While-condition?

I have a program where the user will have the opportunity to choose from multiple strings in order to proceed:
System.out.println("\n\tWelcome! Please choose a song!");
String songChoice = scan.nextLine();
A While-loop is following this code, catching all the inputs that aren't matching the conditions.
while(!songChoice.equals("Stay") || (!songChoice.equals("Hello")) || (!songChoice.equals("Solitude"))
And so on.
I have about fifteen different songs to choose from, and I'm wondering if it's possible to insert an ArrayList in the while-condition instead of writing 15 different conditions for each and one of the strings? Something like...
while(!songChoice.equals(songs)
I've tried around but I can't get it to work... hope someone out there can help me with this!
Please follow the guidelines for a minimum runnable code snippet. Your scanner variable (scan) is not declared and that makes us have assumptions about the way the code works.
A possible solution is to create an ArrayList, populate it with all the strings and check if the input matches one of those strings.
List<String> songList = new ArrayList<>();
songList.add("Some song"); //Repeat until satisfied
System.out.println("\n\tWelcome! Please choose a song!");
String songChoice = scan.nextLine();
while (!songList.contains(songChoice)) {
//Do stuff when input is not a recognised song
}
I heavily recommend checking the javadocs of ArrayList (or any class you struggle with) for any suitable methods/fields. You already found ArrayList, why did you not understand what it does and how to use it?
Use an ArrayList to store songs :
ArrayList<String> availableSongs = Arrays.asList("Hello", "Stay", "Solitude", "Gratitude");
Scanner scan = new Scanner(System.in);
System.out.println("\n\tWelcome! Please choose a song!");
boolean validSongChoosen;
while(!validSongChoosen) {
String songChoice = scan.nextLine();
if(availableSongs.contains(songChoice)) {
validSongChoosen = true;
} else {
System.out.println("\n\tThe song you have choosen is not available");
}
}
Small improvement
Instead of using ArrayList you can use a Set as others also advised. A Set have the particularity to contains only unique non repetitive elements.
This is the cas for your songs. You can't normally have two songs with same name!
So just change your ArrayList with a HashSet

How to store a value for later use? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am a new user and I have a "noob" question. We are being taught Java in school and I have a question about one of our activities. One requirement is to take in student info (such as course) and convert them to a single letter (I assume use .charAt??) and then later on count how many students are enrolled into that course. I have the student info down here:
import java.util.*;
import java.lang.*;
public class CourseTallier
{
public static void main (String[] args)
{
String student = inputStudInfo();
}
public static String inputStudInfo ()
{
Scanner kbd = new Scanner(System.in);
int limit = 0, idnum = 0;
String college = "";
System.out.println("Please input a valid ID number:");
idnum = Integer.parseInt(kbd.nextLine());
if (idnum == 0)
{
System.out.println("Thank you for using this program.");
System.exit(0);
}
while (idnum < limit) {
System.out.println("Invalid ID number. Please enter a positive integer:");
idnum = Integer.parseInt(kbd.nextLine());
}
System.out.println("Please enter a valid course (BLIS, BSCS, BSIS, or BSIT");
college = kbd.nextLine();
while(!college.equalsIgnoreCase("BLIS") && !college.equalsIgnoreCase("BSCS") && !college.equalsIgnoreCase("BSIS") && !college.equalsIgnoreCase("BSIT"))
{
System.out.println("Invalid course. Please enter either BLIS, BSCS, BSIS, or BSIT");
college = kbd.nextLine();
}
return college;
}
public static Character convertCourse (String college)
{
}
and as you can see I am stuck at the "Convert Course" method (modular is required). I was wondering how would I convert something like "BLIS" to a single character "L" and then create another method that counts the number of how many students are enrolled in that course.
I am not asking for someone to complete this program for me cause that would be cheating. I am simply asking someone for a shove in the right direction. Your help is very much appreciated.
Edit: As asked here are the exact requirements:
Program
To the storing for future values, do you know what instance variables are? Unless I misunderstood the question, it seems like it would make sense to make four (static) instance variables that hold the count of users enrolled in each course.
You could either use the .charAt method or use the "switch" statement.
the problem with the charAt method is that you probably can't find different letters for each course using the same indexed letter.(which will bring you to the switch statement again)
To count the number of student enrolled in that course you should have a count variable and increase it every time you convert a course into a single char.
One way would be to use a switch statement
switch(college)
{
case "BLIS":
return("a");
}
Not sure if thats really what your meant to be doing, if your meant to store student data then a Map implementing datastructure would be the go
Well, first of all you need to make your code more modular. How about dividing it into sections,like, getting user input, validating user input, storing user input.
Well to store the user data, you can use something like a HashMap. Keep course as key (eg BLIS) and no of students as value. In start intialize it with 0.
Map<String, Integer> studentCourseHashMap = new HashMap<String, Integer>();
studentCourseHashMap.put("BLIS", 0);
So, every time a user enrolls for the particular course all you need to do is to find the course and increment it by 1. So, for example if a student enrolled for BLIS course. then,
if(studentCourseHashMap.containsKey("BLIS")){
//Checking if BLIS course is available
Integer noOfStudents = studentCourseHashMap.get("BLIS");
//Increment no of students for each enrollment
noOfStudents++;
//Saving the updated value in hashmap
studentCourseHashMap.put("BLIS", noOfStudents);
}
Hope this will help, mention your doubts in comments. :)
why not use a counter for each course and increment it whenever the user enters it.
switch(college)
case BLIS:
blisCounter+=1;
break;
case BSCS:
bscsCounter+=1;
break;
case BSIS:
bsisCounter+=1;
break;
case BSIT:
bsitCounter+=1;
break;
If you want to take each letter from the string, here's the way:
String str = "BLIS";
String strArray[] = str.split("");
for (int i = 0; i < strArray.length; i++) {
System.out.println(strArray[i]);
}
If you want to map the Course String to individual Characters, below is the way:
Map<String, Character> courseMap = new HashMap<String, Character>();
courseMap.put("BLIS", 'L');
courseMap.put("BSCS", 'C');
courseMap.put("BSIS", 'S');
courseMap.put("BSIT", 'T');
for(String courseStr: courseMap.keySet()) {
System.out.println(courseStr + " > " + courseMap.get(courseStr));
}

Java ArrayList, taking user input of multiple types(int, String etc.) in one line

I'm working on getting a little better at Java, and a problem I've run into is taking user input, all in one line like this:
System.out.println("Please input numbers that you would like to work with");
//Read in user input into ArrayList, taking into account that they may input Strings or anything else.
Assuming the user inputs something like this
1, 2, 4, 257, dog, rabbit, 7, #
or even
1 2 4 257 dog rabbit 7 #
I've seen in several places how to read in one input at a time, but I wasn't sure of the best way to read in a dynamic ArrayList all at once.
I'm not really concerned with the difference in doing it with commas or without commas since logically I think I know how to do that, and haven't tried yet, so really the main problem is as stated above (reading user input into ArrayList of dynamic size when user inputs all numbers at once). Thanks, and I'm not necessarily looking for code, this isn't homework, just wondering best way to do this. Just stating logically how it's done will work, but code is appreciated.
try this simple example to print the arraylist values
import java.util.*;
class SimpleArrayList{
public static void main(String args[]){
List l=new ArrayList();
System.out.println("Enter the input");
Scanner input=new Scanner(System.in);
String a =input.nextLine();
l.add(a);
// use this to iterate the value inside the arraylist.
/* for (int i = 0; i < l.size(); i++) {
System.out.println(l.get(i));
} */
System.out.println(l);
}
}
As I think there are enough answers on how to read data from System.in, I'll take a different approach here. First you should be aware that this is not the major way of getting data in java. In fact in more than 10 years I never used it. That's why there's no complete ready to use solution for give me the stuctured data into some container (like ArrayList). Instead you get simply one string per line. And you have to deal with that on your own. this process is called parsing. Depending on the complexity of the chosen syntax there are several approaches like using a parser generator if it's more complex or write the parser by hand in simpler case. I'd like to get into your first suggestion and describe it as comma separated with optional whitespace. For a syntax like this the class Scanner delivers quite some support. Numbers can be recognized and the tokenizing is done almost automatic. However, if you have more specific data you might need some aditional effort, like I demonstrated with a map of animals I used to convert that very special data type. To be flexible enough to solve all the real world problems there can't be a ready to use solution. Only comprehensive support to build your own.
Map<String, Animal> animals = ...
Scanner scanner = new Scanner("1, 2, 4, 257, dog, rabbit, 7, #").useDelimiter(",");
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
result.add(scanner.nextInt());
} else {
String val = scanner.next();
if (animals.containsKey(val)) {
result.add(animals.get(val));
} else {
result.add(val);
}
}
}
you can try this code for taking input dinamically in arraylist and store in arraylist
import java.util.ArrayList;
import java.util.Scanner;
public class HelloWorld
{
public static void main(String []args){
Scanner sc=new Scanner(System.in);
String j;
ArrayList l=new ArrayList();
for(int i=0;i<6;i++)
{ j=sc.nextLine();
l.add(j);
}
System.out.println("Hello World"+l);
}
}
One approach is to tokenize the input and then add it into an array like this:
Scanner scn = new Scanner(System.in);
System.out.println("Put in a set: ");
String input = scn.nextLine();
System.out.println(input);
Scanner tokenizer = new Scanner(input);
tokenizer.useDelimiter(" ");
ArrayList<Object> arr = new ArrayList<Object>();
while(tokenizer.hasNext())
{
arr.add(tokenizer.next());
System.out.println(arr.get(arr.size()-1));
}
System.out.println(arr);

Compare two Lists for Anagrams - Java

I'm currently working on an anagram solver. I saw a really good post which had one recommendation on alphabetizing the letters of both the user input and dictionary list before comparing. It seemed interesting so I'm giving it a try. Previously I used permutations, but I want something that I can eventually (and efficiently) use to solve multi word anagrams.
I can put both my user input and dictionary into char arrays and sorting alphabetically. Now I need to compare each so I can determine if something is an anagram or not. I thought about taking the alphabetized user input and determining if the alphabetized dictionary contained it or not. I've posted my code below. As you can guess I'm a little confused on the logic of this process. I was wondering if someone could help me straighten out the logic a little. Thanks for any help.
public class AnagramSolver1 {
public static void main(String[] args) throws IOException {
List<String> dictionary = new ArrayList<String>();
List<String> inputList = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader("src/dictionary.txt"));
String line = null;
Scanner scan = new Scanner(System.in);
while (null!=(line=in.readLine())){
dictionary.add(line);
}
in.close();
char[] sortDictionary;
char[] inputSort;
System.out.println("Enter Word: ");
String input = scan.next();
inputList.add(input);
//Getting a little confused here. I thought about sorting my input
//then iterating through my dictionary (while sorting it too) and comparing
//thus far it produces nothing
for(int i = 0; i < inputList.size(); i++){
inputSort = inputList.get(i).toCharArray();
Arrays.sort(inputSort);
for (int j = 0; j < dictionary.size(); j++) {
sortDictionary = dictionary.get(i).toCharArray();
Arrays.sort(sortDictionary);
if(inputSort.equals(sortDictionary)){
System.out.println("Anagram" +dictionary.get(i));
} //end if
}//end for
}//end for
}//end main
}
Why not maintain a Map<String, Set<String>> that maps a sorted-character string to a set of strings that are its anagrams. You can update this map as you read words from the dictionary. For example, if you read the word dog you would add an entry to the map "dgo" => {"dog"} (notice that dgo consists of the sorted characters of the word dog). Then if you read the word god, you would sort its characters to obtain the same dgo and consequently amend the previous entry to be "dgo" => {"dog", "god"}. You would of course repeat this for every word in the dictionary.
This should allow for quick and easy querying. If you wanted to then find anagrams of the word dog you would use map.get(sortChars("dog")).
On another note, I'm going to reiterate what the other answer mentioned, namely that it's important to modularize your code. You should put logically related functions/tasks in their own methods as opposed to having everything in one place. This helps with readability and your/others' ability to maintain your code in the future.
You are doing too many things at once here. You've got file IO, user input, sorting and the algorithm all in one place. Try to modularize it so you have a function called isAnagram(List<Character> firstPhrase, List<Character> secondPhrase). Make sure that works correctly, then have all the other steps figure out how to call it. This way you can test your algorithm without requiring user input. This will be a much faster feedback loop.
It's algorithm will work like this:
(optionally) copy the contents of the input so you don't mutate the input
compare their lengths. If they're not equal, return false
sort each list
iterate element by element and check if they're equal. If they're not, return false
if you reach the end, return true.

Check for value in array

I need to check the array to see if the user input is already present, and display a message as to whether it is or isn't there. The first part is working, but I tried to create a method for the word check, and I'm not sure if I'm on the right path or not, cheers.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
int num = array.length, i = 0;
System.out.println("Enter a word");
for (i = 0; i < num; i++) {
while (scan.hasNextInt()) // while non-integers are present...
{
scan.next(); // ...read and discard input, then prompt again
System.out.println("Bad input. Enter a word");
}
array[i] = scan.next();
WordCheck();
}
}
public void WordCheck(String[] i) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter another word");
if (scan.next().equals(array[i])) {
System.out.println("The word has been found");
} else {
System.out.println("The word has not been found");
}
}
}
Right. You've clearly gone down a bad thought process, so let's just clear the slate and have a re-think.
Step one: You want to take some user input
Step two: Compare it with all previous user inputs to see if it's present.
If it is present, return a message indicating that value has been inputted.
otherwise ignore the input and continue execution
Repeat step one.
The solution
So, let's review what you've got, and how you need to change it.
public static void main(String[] args)
If I were you, I would avoid calling methods directly from here. If you do, every method will need to be static, which is a pointless adjustment in scope for the functionality of your class. Create a new instance of your class, inside the main method, and move this code to the class' constructor. This will remove the need to make every single method static.
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
Okay, so you've created a scanner object that takes input from the System.in stream. That's a reasonable thing to do when taking input from the keyboard. You've also created an array to contain each item. If you only want the user to be able to type in 10 values, then this is fine. Personally, I would use an ArrayList, because it means you can take in as many user inputs as the user desires.
Secondly, you want a function to compare the input, with all other inputs. What you have at the moment clearly isn't working, so let's have another go at it.
You will need some input, userInput, and a collection to compare it against, allInputs.
allInputs needs to be accessible from any point in the program, so it's probably wise to make it into a field, rather than a local variable.
Then, because you're comparing userInput against all values, you're going to need a foreach loop:
for(String s : allInputs)
{
if(s.equals(userInput))
{
// Output message code.
}
}
Now the trick is fitting this inside a loop that works with this program. That is up to you.
One simple solution is to use a Set:
Set<String> words = new HashSet<String>();
Add words with the add() method and check if a word is already added with contains(word) method.
EDIT
If you must use Arrays you can keep the array sorted and do a binary search:
Arrays.sort(words);
boolean isAlreadyAdded = Arrays.binarySearch(words, newWord) >= 0;
You're going to have to loop through the entire array and check if scan.next() equals any of them - if so return true - as such:
String toCheck = scan.next();
for (String string : i) { //For each String (string) in i
if (toCheck.equals(i)) {
System.out.println("The word has been found");
return;
}
}
System.out.println("The word has not been found");
This supposes you call WordCheck(), passing the array to it - this method also has to be static for you to call it from the main() method.
You can use the arraylist.contains("name") method to check if there is a duplicate user entry.

Categories