2016-09-04 8 views
-1

beginner 프로그래머가 여기 있습니다. 내 프로그램의 검색 기능에 문제가 있습니다. 목록의 첫 번째 항목을 검색하지 않으면 매력처럼 작동합니다. 작은 배경,이 프로그램 (학교 과제)은 CSV 파일을 읽고 링크 된 목록과 해시 테이블을 만들고 목록을 정렬합니다. 이 과제를 위해 사용자는 이름으로 기고자를 검색 할 수 있어야합니다. 앞서 언급했듯이 George의 이름에서 검색 할 때까지 잘 작동합니다. 필자는 반복자의 현재 값을 출력하기 위해 인쇄 줄을 추가했으며, 결과는 George가 실제로 첫 번째 요소임을 보여 주지만, 그 이름을 검색하면 "찾을 수 없음"이 나타납니다. 나는 조지를 검색 할 때 여기 검색은 Java의 연결된 목록에서 첫 번째 요소를 건너 뛰고 있습니다.

 Iterator<Contributor> nameIter = contributorList.iterator(); 
     boolean result = false; 
     String searchName; 
     System.out.println(contributorData.getFirstName()); //What Name is the iterator pointing at?? 
     System.out.println("Enter the first name of the contributor you are searching: "); 
     searchName = in.nextLine(); 
     String fName = searchName.toLowerCase(); 
     String keyName;   
     while (nameIter.hasNext()){     
      contributorData = nameIter.next(); 
      System.out.println(contributorData.getFirstName()); //What Name is the iterator pointing at?? 
      keyName = contributorData.getFirstName().toLowerCase(); //keyName should equal the above value 
      if (fName.equals(keyName)){ 
       result = true; 
       System.out.println("\nThe following contributor was found:\n"); 
       System.out.printf("%-10s %-10s %-8s %-15s %-17s %s %n", "First", "Last", 
           "Country", "Phone #", "Contribution", "ID"); 
       contributorData.Print();     
      }//end if statement   

     }//end While 
     if (result == false){ 
      System.out.println("\nSorry, but that name was not found!"); 
     } 
     System.out.println("\nPress enter to return to the Main Menu...\n"); 
     in.nextLine(); 

이 출력됩니다 : 다음은 검색 내 코드입니다

조지 < - 가 기여자의 이름을 입력 반복자
에서 현재 값은 검색하고 있습니다 :
조지
조지 < - 이것은 반복기의 값이 George 여야 함을 보여줍니다.
고든 < - 여기에서 검색을 시작하는 이유는 무엇입니까?

마이크

미안하지만, 그 이름을 찾을 수 없습니다!

그래, 나는 여기에서 무슨 일이 일어나고 있는지에 대해 매우 분실했다. 나는 contributorData = nameIter.next(); 주위에 있지만 문제를 해결하지 못하거나 더 많은 원인이 있습니다. 여기있는 도움은 크게 감사하겠습니다.

+0

왜 아래로 투표합니까 ?? –

답변

1

목록에있는 반복기의 경로는 문제가되지 않습니다. 데이터가 공백 인 경우 빈 공간이 생기고 비우지 않으면 비교에 영향을 미치기 때문에 찾을 수 없으며 또한 찾을 수 없는지 확인하십시오. 순서를 뒤집기 위해

Iterator<Contributor> nameIter = contributorList.iterator(); 
    boolean result = false; 
    String searchName; 
    System.out.println("Enter the first name of the contributor you are searching: "); 
    searchName = in.next().toLowerCase().trim();//it is not necessary to use another variable to downcasing 
     //and add .trim() to get rid of blank spaces that may have strings  
    while (nameIter.hasNext()){     
     contributorData = nameIter.next(); 
     if (contributorData.getFirstName().trim().toLowerCase().equals(searchName)){ 
      System.out.println("\nThe following contributor was found:\n"); 
      System.out.printf("%-10s %-10s %-8s %-15s %-17s %s %n", "First", "Last", 
          "Country", "Phone #", "Contribution", "ID"); 
      contributorData.Print(); 
      //break ;if you only want to get the first match uncomment 


     }   
    } 
    if (result == false){ 
     System.out.println("\nSorry, but that name was not found!"); 
    } 
+0

모든 변경 사항을 적용했지만 여전히 작동하지 않습니다. 그래도 여분의 변수를 만들지 말라는 팁을 주셔서 감사합니다. 그러나 여전히 같은 결과를 얻었지만, 다른 모든 이름은 잘 보입니다. 첫 번째 것 (조지)은 .... 내 코드에서 어딘가에있을 수 있습니까? 이것은 스위치 내의 사례입니다 ... 무슨 일이 벌어지고 있는지 전혀 알지 못합니다 ... –

+0

은 첫인상을 남기기 전에 데이터 제공자에게 할당 되었습니까? –

+0

시도해 보았습니다 ... 이상하게 들리지만, .csv 파일의 "George"에 문제가 있다고 생각합니다. 첫 번째 항목을 건너 뛰지 않고 수동으로 다른 참여자를 입력했는데 몇 개의 조지 , 그리고 나는 그것들을 검색하고 인쇄 할 수있다 ... 또한 수동으로 목록의 맨 위에있을 이름을 입력하면 (정렬 됨) 검색하고 찾을 수있다. George Line 내가 검색 할 수는 없지만 ..../ –

0

조건이 충족 될 때 while 루프가 종료되지 않는 한 가지 문제점을 제외하고 프로그램 흐름이 양호 해 보입니다.
조지를 검색 할 때를 의미합니다. 조건이 충족되면 루프를 중지해야합니다.

while (nameIter.hasNext()){     
      contributorData = nameIter.next(); 
      System.out.println(contributorData.getFirstName()); //What Name is the iterator pointing at?? 
      keyName = contributorData.getFirstName().toLowerCase(); //keyName should equal the above value 

      if (fName.equals(keyName)){ 
       result = true; 
       System.out.println("\nThe following contributor was found:\n"); 
       System.out.printf("%-10s %-10s %-8s %-15s %-17s %s %n", "First", "Last", 
           "Country", "Phone #", "Contribution", "ID"); 

       contributorData.Print();  
       break; // this will make the flow exit from the loop  //whenever a condition is met.   
      }//end if statement. 

결과가 좋기를 바랍니다.

+0

노력해 주셔서 감사합니다. 그러나 작동하지 않았습니다. 이름이 발견되면 While 루프를 빠져 나옵니다 ... 목록의 모든 다른 이름이 제대로 작동하면 이름과 모든 것을 인쇄 한 다음 기본 메뉴로 돌아갑니다 (switch 문의 경우) . 내가 제안한 Break를 추가했지만 불행히도 아무 것도 바뀌지 않았습니다 .... –

+0

George가 연결된 목록의 0 번째 색인에 있습니까? 그렇다면 이터레이터를 강화 된 4 루프로 바꾸어보십시오. 이 목록에서 제거 작업을 수행하지 않는다고 생각합니다. Enhanced for도 사용할 수 있습니다. for (Contributor cbtr : conteibutorList) {. (searcName.equals (cbtr.getName) {. // found result}} – Shafique

+0

저는 초급 프로그래머입니다. 이전 수업 만 경험할 수 있습니다 .... 향상된 4 루프는 끝나지 않았습니다. 그래도 내가 그걸로 일할 수 있는지 알아봐, 고마워. –

관련 문제