数组排列完毕后,如何使用 for 循环搜索元素?

按字母顺序排列数组后,我需要添加一个 for 循环操作来搜索其中一个数组中的特定元素。


在这种情况下,我需要搜索“Rogers. Steve”。我应该如何进行?


预先感谢您的所有帮助!


我已经尝试了几个例子,但我无法得到正确的结果......


String[] arrayString=new String[]{

 "Administrator",

 "Vale.Vicky",

 "Lane.Lois",

 "Kent.Clark",

 "Wayne.Bruce",

 "Parker.Peter",

 "Rogers.Steve",

 "Luther.Lex",

 "Osborn.Harry",

 "Tony.Stark"};

String searchString="Rogers.Steve";


//Loop until the length of the array

//Print the index of the string on an array

System.out.println("Rogers.Steve");

我的课。


package helloworldjavabook;


public class HelloWorldjavabook {

  public static void main(String[] args) {


    String[] user = {"Administrator", "Vale.Vicky", "Lane.Lois", "Kent.Clark", "Wayne.Bruce",

      "Parker.Peter", "Rogers.Steve", "Luther.Lex", " Osborn.Harry", "Tony.Stark"};

    orderedGuests(user);

    String[] password = {"PASSWORD1", "ILOVEBRUCE", "ILOVECLARK", "  ILOVELOIS", "IAMGOTHAM", "IAMSPECTACULAR",

      "IAMAMERICA", "IRUNLEXCORP", "IAMGREENGOBLIN", "  IAMINVINCIBLE"};

    orderedGuests(password);

    String id[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};

    orderedGuests(id);

  }


  private static void orderedGuests(String[] hotel) {

    Arrays.sort(hotel);

    System.out.println(Arrays.toString(hotel));

  }


}


Smart猫小萌
浏览 112回答 2
2回答

一只甜甜圈

public void search() {    String[] arrayString = new String[]{      "Administrator",      "Vale.Vicky",      "Lane.Lois",      "Kent.Clark",      "Wayne.Bruce",      "Parker.Peter",      "Rogers.Steve",      "Luther.Lex",      "Osborn.Harry",      "Tony.Stark"};    String searchString = "Rogers.Steve";    Arrays.sort(arrayString);    System.out.println(Arrays.binarySearch(arrayString, searchString));}这其中的关键部分是Arrays.binarySearch(arrayString, searchString)

UYOU

我想你正在寻找这样的东西String[] arrayString=new String[]{&nbsp;"Administrator",&nbsp;"Vale.Vicky",&nbsp;"Lane.Lois",&nbsp;"Kent.Clark",&nbsp;"Wayne.Bruce",&nbsp;"Parker.Peter",&nbsp;"Rogers.Steve",&nbsp;"Luther.Lex",&nbsp;"Osborn.Harry",&nbsp;"Tony.Stark"};String searchString="Rogers.Steve";int position = 0;for (int i = 0; i < arrayString.length; i++) {&nbsp;&nbsp; &nbsp; if(arrayString[i] == searchString ){&nbsp; &nbsp; &nbsp; &nbsp; position = i;&nbsp; &nbsp; }}if( position > 0 ){&nbsp; &nbsp; System.out.println("Position: " + position);&nbsp;} else {&nbsp; &nbsp; System.out.println(searchString + " not found" );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java