New to java and trying to figure out how to print out a specific word in a string array. Eg
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 eg 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.
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
Just use
System.out.println(myArray[1]);
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....
}
}
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).
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.