简体   繁体   English

java字符串数组特定的单词打印出来

[英]java string array specific word print out

New to java and trying to figure out how to print out a specific word in a string array. java的新手,试图弄清楚如何在字符串数组中打印出特定的单词。 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). 我想打印出数组的第二个值(我们说milk ,我知道数组索引从0开始,但只是对于这个例子,我们将使用它)。 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. 我尝试了for循环,但似乎无法实现它,所以如果你们有一个例子,我将不胜感激。

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 [] Array1 = {“bread”,“milk”,“sugar”,“coffee”} String [] Array2 = {“butter”,“tea”,“spoon”,“cup”}所以,如果我提示数组1中的任何条目,例如面包(我希望它打印出类似黄油的东西)那么对于array1中的每个值我想要它返回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]);

Demo at www.ideone.com 在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 如果你想在for循环中进行比较,请使用下面的内容

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 forloop的演示

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). 阅读有关数组Java教程 (或任何Java入门书)。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM