Insert ArrayList into While-condition? - java

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

Related

Comparing an inputted string to multiple strings efficiently

I'm new to Java, and I can't seem to find exactly what I'm looking for on this website. Apologies if it has already been answered in the past!
Essentially, I'm trying to compare a user inputted string to multiple strings pre-established in the program as a "database".
As an example
System.out.println("Enter a name to check the database");
Scanner names= new Scanner(System.in);
String nameinput= names.next();
if(!nameinput.equals( *[ database]?* )
System.out.println("There is no such name, you cannot continue");
How do I check if the inputted string is not equal to the entire database individually?
I have the database set up simply as
class database
{String name, name, name, name... etc.}
I'm trying to stick to keeping things simple and using the database, if at all possible.
I understood that you have a class that contains individual names as fields. It seems like you are looking for a simple collection instead:
List<String> database = Arrays.asList("item1", "item2", "item3");
System.out.println("Enter a name to check the database");
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
if (database.contains(input)) {
System.err.println("There is no such name, you cannot continue");
}
Arrays.asList simply initializes the collection with the 3 items. You can later dynamically add or remove items with database.add or database.remove.
I suggest reading about Java collections and their usage
I suggest to make a list of all the names available in the database. So database class will have a method like
public List getData ()
It will return all the available names. To make the comparison easier, you can try to have the names in the list as uppercase or lowercase using .toUpperCase() or .toLowerCase()
So when you get the input string from user, convert that string to uppercase or lowercase based on your data.
Then simply you can check if this input string is part of list using contains method.
something like,
if(!availableNames.contains(inputName))
System.out.println("There is no such name, you cannot continue");

How would I separate a sentence into individual words with a loop and send them individually into an ArrayList in Java?

I have a very specific problem for my CS course. I have a sentence in a string, and I need that separated into individual words within an ArrayList, and cannot use the split method.
The issue I have is that I have had zero teaching on arrays, only the bare minimum teaching for loops and String statements. I've done a lot of research and figured out the best way to go about making the loop, and sending the words to the ArrayList, however I still can't find a good way to actually have it loop through the sentence and separate each individual word at all. I get how easily it can be done to separate the very first word, however after that I get lost. I have no idea how to make the loop for its other iterations specifically grab the next word in the sentence after the one it previously got.
(Note: The only utilities imported are Scanner, File, HashMap, ArrayList, Random, and *)
What I'm looking for is any tips of specific methods I should try and employ or research. Or perhaps a set of code that is fairly functional in doing something similar to what I'm looking for that I can look at and build my own code off of.
When you said the word "word"(That's weird) I assume that they are separated by spaces. If you are reading in the inputs, then just use Scanner... Then:
Scanner input = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
for(int i = 0;i<numberOfWord;i++){
words.add(input.next());// .next() method read data that are separated by space
}
or:
String theLineOfWord;//Given to you
StringTokenizer st = new StringTokenizer(theLinOfWord);//Used to separate words.
ArrayList<String> words = new ArrayList<String>();
while(st.hasMoreTokens()){
words.add(st.nextToken();
}
or:
public static ArrayList<String> getWords(String line){
ArrayList<String> words = new ArrayList<String>();
line += " ";//add a space to ignore the ending case
while(line.length() != 0) {
words.add(line.substring(0, line.indexOf(' ')));//add the word to the list
line = line.substring(line.indexOf(' ') + 1, line.length());//take out the useless string away
}
return words;
}

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.
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.")
}
}

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.

Categories