0

New to java and trying to figure out how to print out a specific word in a string array. E.g.

String[] myArray = {"bread", "milk", "sugar", "coffee"} 

I want to just print out the second value of the array (we say milk, I know the array index starts at 0 but just for this example we will go with this). Any ideas how to do this. I tried the for loop but cant seem to get it going so if you guys have an example it would be appreciated.

I cant exactly just print out by using index number. I will give a more detailed approach on how i would like it to work... Say I have two arrays String[] Array1 = {"bread", "milk", "sugar", "coffee"} String[] Array2 = {"butter", "tea", "spoon", "cup"} So if I prompted any entry from array 1 e.g. bread (I would like it to print out something like butter then) so for each value in array1 i would like it to return the value at the same index in array2.

2
  • Ok, show the for loop that you tried? May be we can help you solve it using your way only. Commented Feb 17, 2013 at 11:29
  • please specify any specific problem that you are facing Commented Feb 17, 2013 at 11:29

4 Answers 4

1
String[] myArray = {"bread", "milk", "sugar", "coffee"}
for(int i=0;i<myArray.length;i++){
    if(myArray[i].equals("milk")){
       System.out.println(myArray[i]); //Matching the string and printing.
    }
}
System.out.println(myArray[1]); //printing the 2nd element if you don't care about the value
Sign up to request clarification or add additional context in comments.

Comments

1

Just use

System.out.println(myArray[1]);

Demo at www.ideone.com


If you want to compare, use

if (myArray[1].equals("milk")) {
    // your code
}

If you want to compare in for loop, use below

String[] myArray = {"bread", "milk", "sugar", "coffee"};
for (int i=0;i<myArray.length;i++) {
    if (myArray[i].equals("milk")) {
        // your code here....
    }
}

Demo for forloop

Comments

0

If you just need to print one element, you don't need any loop:

System.out.println(myArray[1]); // prints milk, since indices start at 0

Read the Java tutorial about arrays (or any Java introductory book).

Comments

0

You can access any element of array directly using an index. You don't require a loop for it.

For example, if you want to access 2nd element then you have to write:

yourArray[1]
// remember for accessing using index
// always use (index - 1) in this case for 2nd element (2-1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.