2013-11-23 2 views
2

"multiarray"라는 2 차원 배열이 있습니다. 첫 번째는 [7]이고 두 번째는 현재 [500]으로 초기화됩니다. 두 번째 배열로가는 항목이 무작위로있는 텍스트 파일에서 읽는 중입니다. 이 어레이는 절대로 500 개의 엔트리를 가질 수 없으며 얼마나 많은 엔트리가 있는지 알아야합니다.변수를 사용하는 동안 "for"루프에서 array.length를 확인하려고 시도했습니다.

나는 이 내가 알 필요가있는 것을 말해 줄 것이라고 생각했지만 루핑되는 것으로 보인다.

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Formatter; 
import java.util.Scanner; 

public class DOW 
{ 
    public static void main(String[] args) 
    { 
     File file = new File ("/Users/***/RandomInts.txt") ; 
     try 
     { 
     Scanner scanner = new Scanner(file) ; 
     //Formatter formatter = new Formatter (new File ("outputfile.txt")) ; 

     int [][] multiarray = new int [7][500]; 

     int counter1 = 0; 
     int counter2 = 0; 
     int counter3 = 0; 
     int counter4 = 0; 
     int counter5 = 0; 
     int counter6 = 0; 
     int counter7 = 0; 

      while (scanner.hasNext()) 
      { 
       int dow = scanner.nextInt() ; 
       int temp = scanner.nextInt() ; 
       dow = dow -1; 

       if(dow == 0) 
       { 
        multiarray[dow][counter1] = temp; 
        counter1 ++; 
       } 

       if(dow == 1) 
       { 
        multiarray[dow][counter2] = temp; 
        counter2 ++; 
       } 

       if(dow == 2) 
       { 
        multiarray[dow][counter3] = temp; 
        counter3 ++; 
       } 

       if(dow == 3) 
       { 
        multiarray[dow][counter4] = temp; 
        counter4 ++; 
       } 

       if(dow == 4) 
       { 
        multiarray[dow][counter5] = temp; 
        counter5 ++; 
       } 

       if(dow == 5) 
       { 
        multiarray[dow][counter6] = temp; 
        counter6 ++; 
       } 

       if(dow == 6) 
       { 
        multiarray[dow][counter7] = temp; 
        counter7 ++; 
       } 
      } 

      for (int x = 0; x < 7; x++) 
       { 
        int hightemp = 0; 
        int lowtemp = 0; 
        int avetemp = 0; 

        for (int y = 0; y < multiarray[x].length ; y++) 
        { 
         if (multiarray[x][y] > hightemp) 
         { 
          hightemp = multiarray[x][y]; 
         } 

         if (multiarray[x][y] < lowtemp) 
         { 
          lowtemp = multiarray[x][y]; 
         } 

         avetemp = avetemp + multiarray[x][y]; 
        } 
        //avetemp = avetemp/ 
       } 

      //formatter.format (" %d %d \n " , dow , temp) ; 

      //formatter.flush() ; 
      //formatter.close() ; 

      //int[] dow; 
      //dow = new int [7]; 

      //int[] temp; 
      //temp = new int [100]; 

      //int x = 0; 
      //while (x < temp.length) 
      //{ 
       //System.out.println (temp[x]); 
       //++x; 
       //temp[x]=0; 
      //} 
    }   

     catch (FileNotFoundException e) 
     {} 
    } 
} 

배열 길이를 알고 싶은 이유는 일부 수학을 위해 전화를 걸기 때문입니다.

avetemp = avetemp/multiarray[x].length 

이미위한 카운터가 [X]는이 파일에서 읽을 수 있지만 내가 수동으로 모든 것을 쓸 필요가 없었어요 그래서 여기를 사용하지 기대되고있다.

입력 텍스트 파일의 샘플이

:

5 67 
2 -15 
1 -40 
7 32 
6 -24 
7 33 
5 -32 
3 57 
3 41 
6 51 

은 기본적으로 첫 번째 열은 요일이고 두 번째는 온도이다.

+0

ArrayList를 사용하십시오. ArrayList # size() –

+0

배열에 아무것도 넣지 않을 것입니다. 우리는 파일에서 읽는 코드를보고 배열에 내용을 넣어야합니다. – Sanchit

+0

나는 여기에 모든 해답을 가지고 ArrayList 또는 LinkedList를 사용 하겠지만, 만약 당신이 정말로 정말로 기본 배열을 사용해야한다면'Integer' 박스형을 사용할 수 있습니다. 배열에있는 모든 ** - ** null ** 정수를 계산하여 데이터 길이를 얻을 수 있습니다 (배열 길이는 여전히 500입니다). – ADTC

답변

1

를 이제 나는 당신의 입력이 어떻게 생겼는지 알고.

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.Scanner; 

public class DOW { 

    public static void main(String[] args) { 
    File file = new File("/Users/***/RandomInts.txt"); 
    try { 
     Scanner scanner = new Scanner(file); 

     ArrayList<Integer>[] multiarray = new ArrayList[7]; // This is how one would make an array of ArrayList's. 
     for (int i = 0; i < multiarray.length; i++) 
     multiarray[i] = new ArrayList<Integer>(); 

     while (scanner.hasNextInt()) { //This is how you would save the values. You were saving temperatures incorrectly. 
     int dow = scanner.nextInt() - 1; //Get day of week. 
     int temp = scanner.nextInt(); //Get temperature. [Would throw exception here if your input was bad] 
     multiarray[dow].add(temp); //Store temperature in the array representing the day of week. 
     } 

     // Looks like you want to find min, max and average in each column here. 
     for (int x = 0; x < 7; x++) { 
     int hightemp = Integer.MIN_VALUE; // Set this to something really low. (You will see why in a minute) 
     int lowtemp = Integer.MAX_VALUE; // Set this to something really high. 
     double avetemp = 0; // You seem to be using ave as "sum" right now and then you plan on dividing which is fine. This should also be a double. 
     int size = multiarray[x].size(); // No point calling .size() [or in general any function] over and over again. Its better to just cache the answer. 
     for (int y = 0; y < size; y++) { 
      int num = multiarray[x].get(y); // Same logic as size here. 
      hightemp = Math.max(hightemp, num); 
      lowtemp = Math.min(lowtemp, num); 
      avetemp += num; 
     } 
     avetemp = avetemp/size; 
     // P.S.: Also you probably want to save the values of hightemp, lowtemp, avetemp somewhere after doing all this work! 
     // Removed the rest of your code as it is irrelevant for your question. 
     } 
     // Close your streams. 
     scanner.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (Exception e) { 
     // This would happen if your input file is bad. 
     e.printStackTrace(); 
    } 
    } 
} 

편집 : 올바르게 추가하고 있습니다. 내 잘못이야.

+1

그게 전부에요, 내가 필요한 것을 해줍니다. 분명히해야 할 일이 많이 있지만 코드가하는 것을 설명하는 예제와 주석을 고맙게 생각합니다. – thejunioristadmin

0

이 코드에는 별다른 차이가 없지만 길이가 500 인 y 배열을 초기화하면 실제로 채워진 요소 수에 관계없이 길이가 반환됩니다. 필요하다면 파일을 읽은 다음 배열을 초기화하거나 java.util.List를 사용하십시오. 값이 0 일 가능성이없는 경우 0이 아닌 값을 모두 반복하고 처음 0에서 중지 할 수도 있습니다.

+0

나는 이것을 500으로 초기화 했음에도 .length가 얼마나 많은 요소 (?)가 추가 되었는가를 기대했다. 나는 알 수없는 분량의 입장을 위해이 일을해야 할 때 arraylist를 더 가까이에서 보게 될 것이다. – thejunioristadmin

0

Java의 배열은 정적입니다. 즉, 선언 한 공간을 미리 할당 했으므로 , multiarray [y] .length는 실제로 얼마나 많은 항목을 실제로 삽입했는지에 상관없이 항상 500입니다. ArrayList 또는 LinkedList를 대신 사용할 수 있습니다. 모든 공간은 동적으로 할당되어 있으므로 길이에 따라 실제로 얼마나 많은 항목이 있는지 알려줍니다 포함.

0

배열의 크기는 고정되어 있으므로 두 번째 차원의 배열을 길이 500으로 초기화합니다. 배열의 호출 길이는 항상 500을 반환합니다.보다 동적 인 데이터 구조가 필요하면 ArrayList를 고려하십시오. 추가하면 size()가 반환하는 값이 증가합니다.

ArrayList로 전환하지 않으려면 3 차원 배열을 길이가 1 인 3 차원 배열로 변경할 수 있습니다. 두 번째 차원의 크기를 유지할 수 있습니다 .

-

이 당신의 오류에 기여하면 나도 몰라,하지만 당신은 당신의 코드에서 버그를해야합니까. 마지막에 당신의 while 루프는 임시 배열의 외부 접근 시도합니다 : 때문에 당신 ++ X의 (temp.length + 1)로 1 루핑 것

int x = 0; 
while (x < temp.length) { 
    System.out.println(temp[x]); 
    ++x; 
    temp[x] = 0; 
} 

. 대신 루프

사용 A :

for(x=0; x<temp.length; x++) 
{ 
    System.out.println(temp[x]); 
    temp[x] = 0; 
} 
+0

나는 그 영역을 주석해야했다. 나는 아직까지 디버깅을하지 않았으며 그것에 대한 "for"섹션에 중점을 둡니다. 나는 그 코드를 지금 편집 할 것이다. – thejunioristadmin

관련 문제