2014-01-25 6 views
3

나는 이것에 약간의 문제가있어 더 이상 해결책을 생각할 수 없다.Java - 여러 ArrayList에서 값 가져 오기

사용자가 영화 제목 & 극장 이름을 목록에 추가하려고 할 때 결과를 표시하려면 다른 사용자 입력 (년, 월, 일, 시간, 분)이 표시됩니다.

그러나 목록에서 이름/제목이 일치하지 않으면 "귀하의 영화 및/또는 극장을 찾을 수 없습니다."가 인쇄됩니다.

이것은 지금까지 입력 한 코드입니다.

public void addScreening() { 
    System.out.println("-ADD NEW SCREENING-"); 

    String mTitle = Helper.readString("Enter movie title > "); 
    String tName = Helper.readString("Enter theatre name > "); 

    for (int i = 0; i < movies.size(); i++) {for (int j = 0; j < theatres.size(); j++) { 
      if ((movies.get(i).getTitle().contains(mTitle) && movies.get(i) 
        .getTitle() != null) 
        && (theatres.get(j).getName().contains(tName) && theatres 
          .get(j).getName() != null)) { 

       int year = Helper.readInt("Enter year > "); 
       int month = Helper.readInt("Enter month > "); 
       int day = Helper.readInt("Enter day > "); 
       int hour = Helper.readInt("Enter hour > "); 
       int min = Helper.readInt("Enter min > "); 

       screenings.add(new MovieScreening(Helper.thisDate(year, 
         month, day, hour, min), movies.get(i), theatres 
         .get(j), 0)); 
       System.out.println("Added successfully"); 
       break; 
      } else if ((!movies.get(i).getTitle().contains(mTitle)) 
        || (!theatres.get(j).getName().contains(tName))) { 
       System.out 
         .println("Your movie or/and theatre cannot be found."); 
       break; 
      } 
     } 
    } 
} 

목록의 첫 번째 색인을 비교하면 가능하지만 다른 색인과 비교할 수는 없습니다.

하자 영화 & 극장 이름은 "&"b "가 있습니다.

영화 제목 : "A", "B"

극장 이름 : "A", "B"

출력

-Add New Movie Screening- 
Enter movie title > a 
Enter theatre name > a 
// User input 
Added Successfully 
Your movie or/and theatre cannot be found. 
Your movie or/and theatre cannot be found. 
----------- 
-Add New Movie Screening- 
Enter movie title > a 
Enter theatre name > b 
Your movie or/and theatre cannot be found. 
Your movie or/and theatre cannot be found. 
Your movie or/and theatre cannot be found. 
----------- 
-Add New Movie Screening- 
Enter movie title > b 
Enter theatre name > a 
Your movie or/and theatre cannot be found. 
// user input 
Added successfully 
Your movie or/and theatre cannot be found. 
----------- 
-ADD NEW SCREENING- 
Enter movie title > b 
Enter theatre name > b 
Your movie or/and theatre cannot be found. 
Your movie or/and theatre cannot be found. 
Your movie or/and theatre cannot be found. 

는 일반적으로이 입력은 성공한다 목록에는 "a"와 "b"가 있습니다.

Enter movie title > a 
Enter theatre name > b 
----------- 
Enter movie title > b 
Enter theatre name > b 

나는이 문제가 극장의 모든 목록을 통과 할 수 없다고 생각합니다.

여러 목록을 검토하는 방법에 대한 도움말이 필요합니다.

iterator()를 사용해 보았지만 문제도 이와 비슷합니다.

public void addScreening() { 
    System.out.println("-ADD NEW SCREENING-"); 

    String mTitle = Helper.readString("Enter movie title > "); 
    String tName = Helper.readString("Enter theatre name > "); 

    Iterator<Movie> it1 = movies.iterator(); 
    Iterator<Theatre> it2 = theatres.iterator(); 

    while(it1.hasNext() && it2.hasNext()){ 
     Movie a = it1.next(); 
     Theatre b = it2.next(); 
     if((a.getTitle().contains(mTitle)) && (b.getName().contains(tName))){ 
      int year = Helper.readInt("Enter year > "); 
      int month = Helper.readInt("Enter month > "); 
      int day = Helper.readInt("Enter day > "); 
      int hour = Helper.readInt("Enter hour > "); 
      int min = Helper.readInt("Enter min > "); 

      screenings.add(new MovieScreening(Helper.thisDate(year, month, day, hour, min),a,b,0)); 
      System.out.println("Added successfully"); 
      break; 
     }else{ 
      System.out.println("Your movie or/and theatre cannot be found. 2"); 
     } 
    } 

    } 

답변

1

당신이 목록에서 모두 일치, 당신은 else if 성명에서, 각각의 불일치를 인쇄되어있다하더라도, 모든 오류 문을 얻고있는 이유. 오히려 수행해야 할 일은 boolean 변수 found을 가지고 false으로 초기화하는 것입니다. 자, for 루프 안에 if 블록을 넣으십시오. 그리고 if 조건이 충족되면 루프에서 변수를 truebreak으로 다시 설정하십시오.

루프 외부에서 found의 값을 확인하고 false 인 경우 일치하는 것이 없음을 의미합니다.


귀하의 접근 방식에 대한 제안이었습니다. 그러나 나는 여기서 다른 접근법을 따를 것이다.

ArrayList을 사용 중이므로 일치하는 항목이 있는지 찾기 위해 수동으로 반복 할 필요가 없습니다. 당신은 그것에 대해 ArrayList#contains(Object) 방법을 사용할 수 있습니다. 이 메서드는 내부적으로 equals() 메서드를 사용하여 비교하므로 MovieTheatre 클래스 모두에서 equals()hashCode() 메서드를 재정의합니다.Theatre 클래스 마찬가지로

// Movie: 
@Override 
public boolean equals(Object obj) { 
    if (!(obj instanceof Movie)) return false; 

    Movie that = (Movie) obj; 

    return this.title.contains(that.title) || that.title.contains(this.title); 
} 

:

가 여기에 equals 방법의 모습 방법

// Theatre: 
@Override 
public boolean equals(Object obj) { 
    if (!(obj instanceof Theatre)) return false; 

    Theatre that = (Theatre) obj; 

    return this.name.contains(that.name) || that.name.contains(this.name); 
} 

그리고, 당신의 for 루프를 대체 :

String mTitle = Helper.readString("Enter movie title > "); 
String tName = Helper.readString("Enter theatre name > "); 

// Create `Movie` and `Theatre` instance 
// Ideally you would not create a new instance. Rather just fetch them from 
// database, or some `static` list, in case of in-memory implementation. 
// From your implementation, it seems like the entered value might not be the exact 
// match. So that you have to handle. 
Movie movie = new Movie(mTitle); 
Theatre theatre = new Theatre(tName); 

// If you are fetching the movie and theatre from some database or list, then 
// you should just check if `movie` and `theatre` is not `null` 
if (movies.contains(movie) && theatres.contains(theatre) { 
    int year = Helper.readInt("Enter year > "); 
      int month = Helper.readInt("Enter month > "); 
      int day = Helper.readInt("Enter day > "); 
      int hour = Helper.readInt("Enter hour > "); 
      int min = Helper.readInt("Enter min > "); 

      screenings.add(new MovieScreening(Helper.thisDate(year, 
        month, day, hour, min), movies.get(i), theatres 
        .get(j), 0)); 
      System.out.println("Added successfully"); 
} else { 
    System.out.println("Your movie or/and theatre cannot be found."); 
} 
+0

그러나 경우 I for 루프를 내가 추가 한 것과 바꾸고, movies.get (i)를 호출 할 수 없다. & theatres.get (j) 더 이상 –

+1

'movies.get (movies.indexOf (movie));'를 사용할 수 있습니다. –

관련 문제