Searching an ArrayList for String Instance - java

I want to create a code that allows you to put in a word then it searches through the Arraylist, then it sends that code with the new airport codes. I can't figure out how to search through the ArrayList and then print certain letters. One of my friend suggested HashMap, but it only wants me to put in integers for the letters.
import java.util.*;
public class Alphabet {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Put in a word, the machine will then translate it to airport codes!");
String name = in.next();
List<String> name1 = new ArrayList<String>();
name1.add("Alpha");
name1.add("Bravo");
name1.add("Charlie");
name1.add("Delta");
name1.add("Echo");
name1.add("Foxtrot");
name1.add("Golf");
name1.add("Hotel");
name1.add("India");
name1.add("Juliet");
name1.add("Kilo");
name1.add("Lima");
name1.add("Mike");
name1.add("November");
name1.add("Oscar");
name1.add("Papa");
name1.add("Quebec");
name1.add("Romeo");
name1.add("Sierra");
name1.add("Tango");
name1.add("Uniform");
name1.add("Victor");
name1.add("Whiskey");
name1.add("X-Ray");
name1.add("Yankee");
name1.add("Zulu");
for (String string : name1) {
if(name.equals(name1)){
name1.equals(name1);
}
}
System.out.println(name1);
}
}

That was a simple mistake, you are iterating the list but you did not take the string value to check with your name
for (String string: name1) {
if(name.equals(string)){
//Your code
}
}
You can use the following code as well.
name1.forEach(string -> {
if (string.equals(name)) {
System.out.println("found");
} else System.out.println("Not found");
});

Related

How can i compare a string in arraylist with char type of array

Recently i started learning java. And after some knowledge i starts with some program. so i create a Jumble Word game. it works but i have a problem. Here is my code....
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
class JumbleWords
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
ArrayList <String>alist = new ArrayList<String>();
ArrayList <Character>chars = new ArrayList<Character>();
Random rd = new Random();
int listLimit,charLimit,value,ulimit=0,counter=0;
String string,temp;
alist.add("done");
alist.add("nest");
alist.add("rat");
alist.add("cat");
alist.add("hello");
alist.add("cycle");
alist.add("chain");
alist.add("paint");
alist.add("collect");
alist.add("your");
alist.add("gift");
alist.add("card");
alist.add("today");
alist.add("cheer");
alist.add("what");
alist.add("time");
alist.add("share");
alist.add("build");
alist.add("help");
alist.add("success");
alist.add("career");
alist.add("access");
alist.add("learn");
alist.add("course");
alist.add("year");
alist.add("expert");
alist.add("school");
alist.add("floor");
alist.add("season");
alist.add("education");
alist.add("spread");
listLimit = alist.size();
int i=0;
System.out.println();
System.out.println("How many JumbleWords you want to play...");
System.out.println("Max limit is "+listLimit);
ulimit = scan.nextInt();
scan.nextLine();
if(ulimit < listLimit )
{
while(i<ulimit )
{
value = rd.nextInt(listLimit);
string = alist.get(value);
for ( char c : string.toCharArray() )
{
chars.add( c );
}
Collections.shuffle(chars);
Collections.shuffle(chars);
System.out.println(chars);
System.out.println("\nEnter the correct order of the word.");
temp = scan.nextLine();
if(string.equalsIgnoreCase(temp)==true){
System.out.println("You Win......");
System.out.println("(*^*)");
System.out.println();
++counter;
}
else{
System.out.println("You Lose......");
System.out.println("The correct word is :-");
System.out.println(string);
System.out.println("(*_*)");
System.out.println();
}
chars.clear();
alist.remove(value);
i++;
}
System.out.println("Your Score is "+counter+" out of "+ulimit);
System.out.println();
}
else
{
System.out.println("Not enough words we have...");
System.out.println();
}
}
}
now in case of "CHAIN" is suffle and user must input chain for winning but "CHINA" is also a word with same chars. how can i build a logic for that.
You can compare the whole word:
while(i<ulimit )
{
value = rd.nextInt(listLimit);
string = alist.get(value);
if(string.equalsIgnoreCase(value)){
System.out.println("You Win......");
System.out.println("(*^*)");
System.out.println();
++counter;
}
...
First, your code is really not straight readable.
Variable names are very very bad chosen while you implement a specific matter :
a word game.
Besides you declare your variables too early and have also a too broad scope, which is error prone and don't easy the reading too.
How to understand these statements without reading the whole code ?
string = alist.get(value);
Or :
if(string.equalsIgnoreCase(temp)==true){
It should be something like:
String wordToGuess = wordsToGuess.get(value);
and :
if(wordToGuess.equalsIgnoreCase(userInput)){
Instead of using a List of String.
ArrayList <String>alist = new ArrayList<String>();
use a List of WordToGuess where each instance will store a List<String> anagrams where WordToGuess could be declared :
public class WordToGuess{
private List<String> anagrams;
...
public WordToGuess(String... anagrams){
this.anagrams = Arrays.asList(anagrams);
}
public String getAnyWord(){
return anagrams.get(0);
}
public boolean contains(String word){
return anagrams.contains(word.toLowerCase());
}
}
In this way you have just to check if the input of the user is contained in the List.
So
ArrayList <String>alist = new ArrayList<String>();
will become :
List<WordToGuess> wordsToGuess = new ArrayList<WordToGuess>();
Favor the interface in the variable type declaration over concrete class.
And you could populate your List in this way :
wordsToGuess.add(new WordToGuess("done", "node")); // two possibilities
wordsToGuess.add(new WordToGuess("nest")); // one
...
wordsToGuess.add(new WordToGuess("chain", "china")); // two
...
And the comparing input String with the expected String :
if(wordToGuess.equalsIgnoreCase(userInput)){
will become :
if(wordsToGuess.contains(userInput)){
It is better to keep the ignoring-case task in the provider class that in the client class that may forget it.

Storing data in an Array and outputting that data

I am working on a program that stores data in an Array from the user and outputs that data.
For example:
An input:
Happy HAPPY#foo.com
The output:
NAME: Happy
EMAIL: HAPPY#foo.com
I was hoping someone could look at what I've got so far and give me a pointer on how to continue. I know I have to use the scanner class and scan.nextLine, I'm not sure what comes next. I understand I don't have much, I'm not looking for someone to complete this, but maybe someone who can give me some pointers or point me in the right direction. I believe I have the correct base to my program.
My Code So Far:
import java.util.ArrayList;
import java.util.Scanner;
public class Program5 {
void loadContacts()
{
Scanner scan = new Scanner(System.in);
System.out.println(scan.nextLine());
scan.close();
}
void printContacts()
{
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Program5 program5 = new Program5();
program5.loadContacts();
program5.printContacts();
}
}
Better name the class "person" or like this, but nevermind for the explanation :
public class Program5 {
private String name;
private String mail;
public Program5(){}
void loadContacts(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a name and a mail like this : name email#email.com (separate with ' ')");
String[] line = scan.nextLine().split(" ");
while(line.length!=2){
System.out.println("Again, enter a name and a mail like this : name email#email.com (separate with ' ')");
line = scan.nextLine().split("/");
}
this.setName(line[0]);
this.setMail(line[1]);
scan.close();
}
void printContacts() {
System.out.println("NAME : "+this.name+"\nEMAIL : "+this.mail);
}
public static void main(String[] args) {
Program5 program5 = new Program5();
program5.loadContacts();
program5.printContacts();
}
public void setName(String name) {
this.name = name;
}
public void setMail(String mail) {
this.mail = mail;
}
}
In the loadyou ask the user, check it he enter 2 element separate by '/' and if yes store them as attributes to be able to get them in another method ;)
You should have a global varible to store the name and the email. Try adding these lines on the top of the code. after public class Program5 {.
private String Name, Email;
The you must assing this values to void loadContacts(). Spliting the string you read.
void loadContacts()
{
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String arr[] = input.split("\\s+");
Name = arr[0];
Email = arr[1];
scan.close();
}
And finally on void printContacts().
void printContacts()
{
System.out.println("NAME: " + Name + "\nEMAIL: " + Email);
}
Here is the code runnig: http://ideone.com/mjyfHK
You can do a variety of things.
You can make loadContacts() and printContacts() static methods, and also change loadContacts() so that it returns an Array or 2D array or however you choose to represent a name-email pair. Then change printContacts()` to take in that type and iterate through that Array to print out each name/email pair. This solution is a bit more work but you won't have to create an object of the same class within the main method of that class.
or
You can keep your method as they are and instead create a new field for the program class, called contacts and it would be of the type that you choose for representing name/email pairs. You would add items to contacts in loadContacts() and iterate through it in printContacts(). Then you don't have to change anything in your main method.

Shortcut to Checking a String in a While Loop for Java?

I'm completely new to Java programming. I'm wondering if there's a shortcut to checking an input String with many preset possibilities. As an example, I'm trying to check to see if the input matches up to specific Strings, and if it doesn't, I want it to go through a while loop until the spelling errors made by the user have been corrected.
But instead of writing
!string.equalsIgnoreCase("badstring")) && !string.equalsIgnoreCase("badstring2")) &&
!string.equalsIgnoreCase("badstring3")) && ...
etc. for, say, 40 different string possibilities, is there an easier way to write it?
Or do I just need to write
!__.equalsIgnoreCase("__") && ...
over and over?
It's best to use Java's new aggregate operations feature for your problem. Here's how you could do it:
import java.util.ArrayList;
class TestStrings {
public static void main(String... args) {
String tester = "Some string";
ArrayList<String> badStrings = new ArrayList<>(1),
result = new ArrayList<>(0);
badStrings.add("Bad string 1");
badStrings.add("Some string");
// add more strings;
// filter out good strings
badStrings.stream().filter((s) -> {
// the filter
return tester.equals(s);
}).forEach((s) -> {
// fill the result list with the good strings
result.add(s);
});
System.out.println(result.toString());
}
}
You could store your bad strings in a Collection, and check your input by looping through the collection.
List<String> badStringList = new ArrayList<>();
badStringList.add("badString 1");
badStringList.add("badString 2");
badStringList.add("badString 3");
...
badStringList.add("badString N");
for (String badString : badStringList){
if (!inputString.equalsIgnoreCase(badString))) {
doSomething();
}
}
I think instead of checking what you dont want check what you want, for e.g. in below code i want the word "Hello" as input so i'm checking only "Hello".
Please elaborate if something else is expected.
import java.util.Scanner;
public class StringEquals {
public static void main(String[] args) {
while(true){
Scanner kbd=new Scanner(System.in);
String input=kbd.nextLine();
if(input.equalsIgnoreCase("Hello")){
System.out.println("String matched");
System.out.println("Please try again");
break;
}
}
}
}

How to search in a list for a part of a string and print out the whole string?

I made a code which uses one input and store it in a genertic list and then I use another input to compare it with the first input ... If the first input is "Eric 1991" while the second input is just "Eric" so I want to print out all the sequence like this "Erik 1991" .. I used different ways to search in the namebirthday list , I used for loop then I used contains but they seeme do not work ,, Now I use toLowerCase().contains(x.toLowerCase()
I am getting error in eclipse in line of toLowerCase().contains(x.toLowerCase()
How can I correct that line to run the code???
package shapes;
import java.util.ArrayList;
import java.util.Scanner;
public class Base {
public static void main(String [] args) {
ArrayList<String> namebirthday = new ArrayList<String>();
Scanner sn = new Scanner(System.in);
String n=sn.nextLine();
// String k=sn.nextLine();
// String m=sn.nextLine();
namebirthday.add(n);
// namebirthday.add(k);
// namebirthday.add(m);
Scanner sb = new Scanner(System.in);
String x=sb.nextLine();
if (namebirthday.toLowerCase().contains(x.toLowerCase())){ // The method toLowerCase() is undefined for the type ArrayList<String>
System.out.println(namebirthday);
} else {
System.out.println("x" +"is not found" );
}
}
}
Acually I tried to put if (((String) namebirthday).toLowerCase().contains(x.toLowerCase())){ but eclipse says "Cannot cast from ArrayList to String- The method toLowerCase() is undefined for the type ArrayList"
What to do???
thanks
You have to use foreach to get the element form your lest and then do your comparison.
If you use namebirthday.contains then this will won't work for input is like "Eric".
See following code:
for(String currentString : namebirthday){
if (currentString.toLowerCase().contains(x.toLowerCase())){
System.out.println(currentString );
} else {
System.out.println("x" +"is not found" );
}
}
Cannot cast from ArrayList to String- The method toLowerCase() is
undefined for the type ArrayList
if (namebirthday.contains(x.toLowerCase())){
System.out.println(x);
} else {
System.out.println("x" +"is not found" );
}
}
You cannot use toLowerCase() in on a list. You have to implent yourself the contains method.
private static boolean containsIgnoreCase(List<String> nameBrithday, String s) {
for (String s1 : nameBrithday){
if ( s1.toLowerCase().contains(s.toLowerCase())){
return true;
}
}
return false;
}
You can't call toLowerCase() on the array, you have to call it on each of the members of the array:
boolean found = false;
for(String nm : namebirthday) {
if (nm.toLowerCase().contains(x.toLowerCase())) {
System.out.println(nm);
found = true;
// Add a break; here if you only care about the first match
}
}
if(!found) System.out.println("x" +"is not found" );
namebirthday is a List instance, not a String one. If you want to check something on content of this list, you need to get a single element that is a String. I am posting two examples how you can do it (the first one is probably more useful for you):
Check if the list contains the element
if (namebirthday.contains("Erik 1991")) {
// Do something
}
Iterate whole list and do the checking on each element
for (String element : namebirthday) {
if (element.equals("Erik 1991")) {
// Do something
}
}
Here is the fixed code
package shapes;
import java.util.ArrayList;
import java.util.Scanner;
public class Base {
public static void main(String [] args) {
ArrayList<String> namebirthday = new ArrayList<String>();
Scanner sn = new Scanner(System.in);
String n=sn.nextLine();
// String k=sn.nextLine();
// String m=sn.nextLine();
namebirthday.add(n);
// namebirthday.add(k);
// namebirthday.add(m);
Scanner sb = new Scanner(System.in);
String x=sb.nextLine();
for (String str : namebirthday){
if (str.toLowerCase().contains(x.toLowerCase())){
System.out.println(str);
} else {
System.out.println("x" +"is not found" );
}
}
}
}

Separate a comma separated value in an array list then put it back together

What I am trying to do exactly is creating a sorting program that sorts PatientRecords by whatever the user specifies in the command-line.
The program is operated on command-line and the user will input a text file containing the records as the first argument (args[0]), and how he wants it sorted as the second argument(args[1]).
The text file is formatted as: Lastname, Firstname, Age, Roomnumber for each line.
The amount of Lines is not specified and can vary, therefore I am using an Array list.
I can read in the lines and I got to where I could sort it by last name, but it looks like to me that the only way to do it is by separating the line at the commas and apprehending them individually in separate methods.
If there is a better way please let me know, I am open to anything. My main problem is getting the program to sort by the different categories, such as Age or RoomNumber.
Here is my code:
import java.io.*;
import java.util.*;
public class PatientRecord
{
public static void main(String args[]) {
System.out.println("Servando Hernandez");
System.out.println("Patient sorting Program.");
Scanner scan = null;
try
{
scan = new Scanner(new File(args[0]));
}
catch (FileNotFoundException e)
{
System.err.println("File path \"" + args[0] + "\" not found.");
System.exit(0);
}
ArrayList<String> lines=new ArrayList<String>();
while(scan.hasNextLine())
lines.add(scan.nextLine());
if(!(args.length == 0))
{
if(args[1] == lastname)
{
sortByLastName();
}
else if(args[1] == firstname)
{
sortByLastName();
}
else if(args[1] == age)
{
sortByAge();
}
else if(args[1] == roomnumber)
{
sortByRoomNumber();
}
}
}
static String sortByLastName()
{
Collections.sort(lines);
for(String x : lines)
System.out.println(x);
}
static String sortByFirstName()
{
}
static int sortByAge()
{
}
static int sortByRoomNumber()
{
}
}
Create a model class named Patient which has firstName, lastName etc.
class Patient{
String firstName;
String lastName;
// Constructor, getter, setter
}
I guess, text file line are comma separated. So, split the line into array and populate the List
List<Parent> patients= new ArrayList<>();
while(sc.hanNextLine()){
String[] values= sc.nextLine().split(",");
patients.add(new Patient(...))
}
Now, read the customer preferences from command line and sort the patients List.
String sortType= sc.next()
switch(sortType)){//Use java 7 or greater for string switch
case "firsname":
//Now sort the list by firstname using Comparator sort method.
break;
case "lastname":
....
}

Categories

Resources