使用startsWith()搜索数组

时间:2015-10-13 07:21:42

标签: java arrays

我正在寻找使用startsWith()在数组中搜索的一些帮助。

我希望用户输入名字,搜索数组,如果名字匹配,请打印:员工ID号,姓氏,名字。

如果没有匹配项,请返回一条简单的错误消息。

下面的代码搜索数组,打印匹配的员工,但也会继续打印错误消息,直到它遍历整个数组。

目前的输出:

import urllib3
import certifi
wsdl_url = 'blabla'
http = urllib3.PoolManager(
    cert_reqs='CERT_REQUIRED', # Force certificate check.
    ca_certs=certifi.where()  # Path to the Certifi bundle.
)
certifi.where()
# You're ready to make verified HTTPS requests.
try:
    r = http.request('GET', wsdl_url)
    print r
except urllib3.exceptions.SSLError as e:
    print "wrong"
    # Handle incorrect certificate error.

如何将其更改为仅返回匹配,如果不匹配,则只返回错误消息。

感谢您的帮助!

ID No: 2345 - Holt, Steve
ID No: 2345 - Molt, Steve
ID No: 2345 - Sholt, Steve
ID No: 2345 - Colt, Steve
No Matching employee records found!
No Matching employee records found!
No Matching employee records found!
No Matching employee records found!
...

5 个答案:

答案 0 :(得分:5)

问题位于false循环中。您基本上是为每个不符合您描述的员工打印错误消息。

要解决此问题,您只需拥有一个布尔标志,调用empFound,最初设置为break。当您通过您的员工时,如果找到匹配项,那么您只需将for设置为true并将empFound设置为循环。

false循环之外,当且仅当break <div class="collapse navbar-collapse" collapse="menuCollapsed" ng-click="collapse()"> <ul class="nav navbar-nav navbar-right nav-link"> <li ui-sref-active="active"> <a href ui-sref="home"> <i class="fa fa-home"></i> Home </a> </li> <li ui-sref-active="active"> <a href ui-sref="service"> <i class="fa fa-info-circle"></i> Service </a> </li> <li ui-sref-active="active"> <a href ui-sref="portfolio"> <i class="fa fa-briefcase"></i> Portfolio </a> </li> <li ui-sref-active="active"> <a href ui-sref="team"> <i class="fa fa-users"></i> Team </a> </li> <li ui-sref-active="active"> <a href ui-sref="testimonial"> <i class="fa fa-comments"></i> Testimonial </a> </li> <li ui-sref-active="active"> <a href ui-sref="contact"> <i class="fa fa-envelope"></i> Contact </a> </li> </ul> </div> </div> </div> <div ui-view="main"> </div> 时,才会显示错误消息。

正如@vvs指出的那样,这里提出的解决方案将在您找到匹配后停止,也就是说,它最多会产生1次点击。如果要列出以您所使用的字符串开头的所有员工,只需省略<div class="banner"> <div class="intro-body"> <h1>CREATIVE DIGITAL<br> SOLOUTIONS</h1> <p>Proin iaculis consequat sem cure.</p> <a href ui-sref="portfolio" class="btn btn-success">VIEW PORTFOLIO</a> </div> </div> angular.module( 'ngBoilerplate.home', [ 'ui.router', 'plusOne' ]) /** * Each section or module of the site can also have its own routes. AngularJS * will handle ensuring they are all available at run-time, but splitting it * this way makes each module more "self-contained". */ .config(function config( $stateProvider ) { $stateProvider.state( 'home', { url: '/home', views: { "main": { controller: 'HomeCtrl', templateUrl: 'home/home.tpl.html' } }, data:{ pageTitle: 'Home' } }); }) /** * And of course we define a controller for our route. */ .controller( 'HomeCtrl', function HomeController( $scope ) { }) ; 语句即可。这将导致循环继续并检查所有员工元素。

答案 1 :(得分:0)

我认为他想打印所有匹配的就业,因此休息不会解决它。 如果您找到至少一名具有特定姓名的员工,您应该做的是拥有一面旗帜。

boolean atLeastOneFound = false;
for (int i = 0; i < employeeList.length; i++){
    if (employeeList[i].getFirstName().startsWith(nameCheck)){
        System.out.println(...);
        atLeastOneFound = true;
    }
}
if (!atLeastOneFound) {
    System.out.println("No Matching employee records found!");
}

答案 2 :(得分:0)

您可以使用Java 8流轻松完成此任务:

public static void main(final String[] args) throws Exception {
    Scanner scanner = new Scanner(System.in);
    Employee[] employees = {
            new Employee("Steve", "Holt", "2345"),
            new Employee("Steve", "Molt", "2111"),
            new Employee("Steve", "Sholt", "245"),
            new Employee("Steve", "Colt", "2222"),
            new Employee("Steve", "Wolt", "25"),
            new Employee("Boy", "Blue", "1"),
            new Employee("Boy", "Wonder", "8999"),
            new Employee("Boy", "George", "500"),
            new Employee("Will", "Smith", "123"),
            new Employee("Will", "Ferret", "23")
    };
    String prefix = scanner.nextLine();
    List<Employee> matches =
            Arrays.stream(employees).filter(e -> e.getFirstName().startsWith(prefix)).collect(Collectors.toList());

    if (matches.isEmpty()) {
        System.out.println("No Matching employee records found!");
    } else {
        matches.stream().forEach(System.out::println);
    }

    scanner.close();
}

如果你不能使用流,你必须遍历数组并自己构建matches列表。

我移动了

System.out.println("ID No: " + employeeList[i].getIdNum() + " - "
                           + employeeList[i].getLastName() + " " +
                           employeeList[i].getFirstName());

部分加入toString类的Employee方法,如下所示:

public String toString() {
    return String.format("ID No: %s - %s %s", id, lastName, firstName);
}

因此,我们只能编写matches.stream().forEach(System.out::println);来打印所有匹配的员工。

答案 3 :(得分:-1)

在if块中插入{{1}}语句,因为你的for正在执行,直到循环结束

{{1}}

答案 4 :(得分:-2)

声明标志isFound = false;

添加休息时间:

if (employeeList[i].getFirstName().startsWith(nameCheck)){
                System.out.println("ID No: " + employeeList[i].getIdNum() + " - "
                                   + employeeList[i].getLastName() + " " +
                                   employeeList[i].getFirstName());
                 isFound = true;
                 break;
            }

并从循环中删除错误消息。 循环外检查:

if(isFound) {
// print message
}
相关问题