Win a copy of Mastering Corda: Blockchain for Java Developers this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

Comparing to a large number a strings?

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a way to compare a large quantity of strings? Such as if you were to see if the user input string was a valid pet.

Is there a way to compare it to "dog" "cat" "bird" etc without using A LOT of if statements?

I could use string.split but then how exactly is that stored in an array?
 
lowercase baba
Posts: 12954
65
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
somewhere, you're going to have to build all the string you want to compare against. I would consider putting all of them in a set. Then, when you get your new string, you just check to see if it is already in there.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
May be kind of late but...

Switch(string name){
case "dog":
System.out.println(string name);
Break;
Case "cat":
System.out.println("kitten");
Break; }

This takes the variable (your string) and in the case that it equals "dog" it performs the code until it gets to "break;"
It's basically a lot of if statements.
 
Ranch Hand
Posts: 174
Java ME Opera Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think switching strings is possible only in java 7.
Anyways, I thing the best solution is regex:

 
Ranch Hand
Posts: 300
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If you need to compare multiple strings , try using regex as suggested by Zandis, regex is best for string matching and many methods in string e.g. replace, split etc support regex.
 
fred rosenberger
lowercase baba
Posts: 12954
65
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i guess the question is:

do you need to compare a lot of user inputs to a few possible string, or so you need to compare a few user input strings to a large list of possible strings?

I would approach these differently.
 
reply
    Bookmark Topic Watch Topic
  • New Topic