为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Smart猫小萌 2023-12-13 10:10:08
按字母顺序排列数组后,我需要添加一个 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 arraySystem.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));  }}
查看完整描述

2 回答

?
一只甜甜圈

TA贡献1836条经验 获得超5个赞

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)


查看完整回答
反对 回复 2023-12-13
?
UYOU

TA贡献1878条经验 获得超4个赞

我想你正在寻找这样的东西


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";


int position = 0;

for (int i = 0; i < arrayString.length; i++) { 

    if(arrayString[i] == searchString ){

        position = i;

    }

}

if( position > 0 ){

    System.out.println("Position: " + position); 

} else {

    System.out.println(searchString + " not found" );

}


查看完整回答
反对 回复 2023-12-13
  • 2 回答
  • 0 关注
  • 111 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信