• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array question  RSS feed

 
Volert Charles
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello! I'm new to the forums, programming, and Java itself. I would appreciate any help at all.

The problem: I'm trying to register an int that is the position of a certain String in an array, based on user input.
I'll give an example to clarify:

String[] months = {"January", "February", "March", "April", "May"...} //Assume all 12 months are in the array
System.out.println("What month?");
Scanner getMonth = new Scanner(System.in);

I want the month that the user inputted to be read and matched to the position of the month in the array...and then I want to do some other stuff with the int that it produces.

How can I do this?

Thank you in advance!
 
Paweł Baczyński
Bartender
Posts: 2054
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Loop through the array, compare each element with the user input. If one equals the other you have found your result. If you went through the entire array and didn't find anything that means that there is no such String in the array.
 
Campbell Ritchie
Marshal
Posts: 55785
164
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Have you been told specifically to use arrays? There are better ways to do it, possibly with an enumerated type.
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Volert Charles wrote:The problem: I'm trying to register an int that is the position of a certain String in an array, based on user input....

I hate to say, but that's very vague. How do you want to match?

For example:
If your user enters "January", then it seems fairly certain that you will want to return the "position" of the first element in your array.

But what if they enter "january" (small 'j')? Do you still want your program to match the first element? And what about "Jan", or "jan" ... or even "J"?

Next: What do you mean by a "position"? In Java, indexes start from 0, so if you want "January" to return 1, and "February" 2...etc, you'll need to do a bit of 'magic'.

So, my advice: Write down precisely what you want your program to do, in detail, and ask us the question again (if you need to).

HIH

Winston
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!