2013-05-19 6 views
0

결합 된 값이 가장 높은 3D 배열의 요소 그룹을 알아낼 방법이 있습니다. 나는 배열을 통과하는 데 사용하는 중첩 루프가 3 개 있으며 특정 조건이 충족 될 때 변수를 변경하려고합니다. 그러나 변수 중 어느 것도 사용되지 않습니다. 나는 int yint m을 바꾸기 위해 sumtotal을 초과하면 for 루프의 반복을 반복한다.왜 내 변수가 내 루프에서 변경되지 않습니까?

감사합니다. 여기 내 코드입니다 :

public void wettestMonth(){ 
     double sum = 0; 
     double total = 0; 
     int y = 0; 
     int m = 0; 

     //cycle through each year and month 
     for(int i = 0; i < 34; i++){ 
      for(int j = 0; j < 12; j++){ 
       //reset the current month to 0 after each month has been cycled through 
       sum = 0; 
       for(int k = 0; k < 31; k++){ 
        //only add the record if the current entry is not null (-99.99) 
        if(sortedData[i][j][k] != -99.99){ 
         sum += sortedData[i][j][k]; 
        } 
        //if the current month is wetter than the wettest one, make the current month the new wettest one 
        if(sum > total){ 
         total = sum; 
         y = i; 
         m = j; 
        } 
       } 
      } 
     } 

     JOptionPane.showMessageDialog(null, "The wettest month on record was " +m +y, "Wettest Month.", JOptionPane.PLAIN_MESSAGE); 

    } 

편집, 난 그냥 잠시 대신 루프 내가 문제 라인으로 보이는에 범위를 벗어날 오류가있어 그것을 재구성, if(sortedData[i][j][k] != -99.99)

편집 2 내가 선언하고 sortedData[][][]

공용 클래스 GetData의를 초기화 곳, 여기 {

//initialises an array that holds 34 years, each with 12 months, each of which has 31 entries for reach day 
public double[][][] sortedData = new double[34][12][31]; 

//initialises a new scanner named rainFile 
private Scanner rainFile; 

//method for opening the file 
public void openFile() { 

    try{ 
     //as the input for the scanner we use the rainfall file 
     rainFile = new Scanner(new File("C:\\\\Users\\\\admin\\\\Documents\\\\NetBeansProjects\\\\110_term3\\\\WeatherDataFiles\\\\rainfall.txt")); 
    } 
    catch(Exception e){ 
     //if no file has been found a JOptionPane will display an error message telling the user to double-check the file path 
     JOptionPane.showMessageDialog(null, "Check the file path is correct.", "No file found!", JOptionPane.ERROR_MESSAGE); 
    } 
} 

//method for reading the file 
public void readFile(){ 

    //ignore the first 3 lines in the data file 
    String dump1 = rainFile.nextLine(); 
    String dump2 = rainFile.nextLine(); 
    String dump3 = rainFile.nextLine(); 

     //these nested for loops will dictate the current index of sortedData 
     for(int i = 0; i < 34; i++){ 
      for(int j = 0; j < 12; j++){ 

       //ignores the year and month at the start of each line 
       String dump4 = rainFile.next(); 
       String dump5 = rainFile.next(); 

       //this final nested for loop dictates the final index of sortedData 
       for(int k = 0; k < 31; k++){ 

        //asigns the current value of scanner rainFile to String a 
        String a = rainFile.next(); 

        //converts the String a to a double type and then assigns it to the current index of sortedData 
        double dbl = Double.parseDouble(a); 
        sortedData[i][j][k] = dbl; 
       } 

      } 
     } 

    } 
+2

이것은 ... – home

+2

제안 몇 가지 단위 테스트를 디버그 모드에서 응용 프로그램을 시작 및/또는 쓰기 할 때입니다)) 주어진 정확한 입력 3D 배열을 일을 기대 디버거에서. "sortedData [i] [j] [k]"가 "-99.99"와 같은지 확인하십시오. "합계"및/또는 "합계"가 계속 증가하는지, 어디에서 참조하십시오. – paulsm4

+0

'sortedData'가'double [] [] []'이고 값이 부재중 인 데이터에 대해 명시 적으로'-99.99'로 설정되면 비교는 의도 한대로 작동하거나 [JVM이 완전히 망가졌습니다]. 'sortedData'가'float [] [] []'이면,'sortedData! = -99.99'는'true'로 대체 될 수 있습니다. 저는 사지에 나가서'sortedData'가'float [] [] []'라고 생각합니다. (당신은 센티넬로'-100'을 사용하거나'! = -99.99f'를 체크 할 수 있습니다.) –

답변

3

는 매달 합계를 인쇄 시도 되세요 ?

가장 명백한 가능성은 버그가있는 동등성 검사로 인해 합계가 항상 0보다 작다는 것입니다. 값이 정확히 -99.99 라운드에하지 않는 한이 라인에 대한

,

sortedData[i][j][k] != -99.99 

그것은 사실 일 것입니다. 이것은 의도하지 않을 수 있습니다. 예를 들어, 어떻게 든 부동 소수점 수학을 통해 값을 구성하는 경우 반올림 오류로 인해 정확히 동일한 값을 얻지 못할 가능성이 높습니다. 게다가, 이와 같은 이상한 센티널 값의 사용은 오류가 발생하기 쉽고 읽기 쉽지 않습니다. 가능한 경우 NaN과 같은 명백한 감시 가치를 사용하는 것이 좋습니다.

문제를 보려면 값이 약간 다른 경우 어떻게 될지 고려하십시오. 말해봐, -99.99000001. 그런 다음 첫날이 지나면 이미 음수 값을가집니다. 한 달 후에 합계는 대략 -3099.69000031이며 0보다 훨씬 작습니다. 합계가 항상 음수이므로 원래의 총계 0보다 결코 좋지 않으므로 최선의 업데이트가 이루어지지 않습니다.

아마도 하루 루프 외부에서 업데이트 검사를 이동하려고 할 수도 있습니다. 이 부분은 전체 월에 대해 합계를 사용하는 것으로 보이지만 매월 부분 합계로 실행합니다. 추가되는 값이 음수가 아닌 한 잘못된 결과가 실제로 발생하지는 않지만 (아마도 앞서 언급 한 버그로 인한 것이 아닐 수도 있지만) 여전히 수정해야합니다.

   if(sum > total){ 
        total = sum; 
        y = i; 
        m = j; 
       } 
+0

'sortedData [i] [j] [k]! = -99.99' 행에서 NetBeans는 힌트'invert if'를 계속 제공합니다. 이것이 잘못된 일에 대한 단서가 될 수 있습니까? 업데이트 확인에 대한 정보를 제공해 주셔서 감사합니다. – JmJ

+0

@Josh 나는 그것이 무관계하다고 생각합니다. – Antimony

0

코드에 아무 것도 표시되지 않습니다.

아마도 다음과 같은 조건이 사실 일 수 있습니까?

if(sortedData[i][j][k] != -99.99) 
+2

조건이 항상 사실로 밝혀 질 가능성이 훨씬 높습니다. –

+0

항상 true로 밝혀지면 ... 합계가 0보다 클 수 없습니다. – vivoconunxino

0

조심스럽게, 루프에 대한 내부의 크기 검사, 루프의 결승에 바르 이동 한 경우 당신이하고있다 나에게 나타납니다 제공되었습니다 첫 번째 코드를 검토 몇 가지 더 추가 코멘트.

Eclipse 디버그를 통해 스윙 응용 프로그램을 실행하고 응용 프로그램의 각 행에서 얻은 결과를 확인할 수 있습니까?코드를 통해 단계 :

/** 
* This method calculates the wettest month during the certain period of time. 
*/ 
public void wettestMonth(){ 
    double sum = 0; 
    double total = 0; 
    int y = 0; 
    int m = 0; 
    final int numberOfYearsToCycleThrough = 34; 
    final int numberOfMonthsToCycleThrough = 12; 
    //cycle through each year and month 
    for (int i = 0; i < numberOfYearsToCycleThrough; i++) { 
     for (int j = 0; j < numberOfMonthsToCycleThrough; j++) { 
      sum = 0; 
      for (int k = 0; k < 31; k++){ 
       //only add the record if the current entry is not null (-99.99) 
       if (sortedData[i][j][k] != null && sortedData[i][j][k] != -99.99) { 
        sum += sortedData[i][j][k]; 
       } 
      } 
     //if the current month is wetter than the wettest one, make the current month the new wettest one 
      if (sum > total) { 
       total = sum; 
       y = i; 
       m = j; 
      } 
     } 
    } 
    JOptionPane.showMessageDialog(null, "The wettest month on record was " +m +y, "Wettest Month.", JOptionPane.PLAIN_MESSAGE); 
} 
관련 문제