2

I have a two dimensional array named "multiarray." The first is [7] , the second is initialized currently as [500]. I am reading in from a text file that has a random number of entries going to the second array. The array will never have 500 entries and I need to know how many entries there are.

I was thinking that y < multiarray[x].length would tell me what I needed to know but it seems to be looping.

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)
        {} 
     }
}

The reason I want to know the array length is because I want to call the number in for some math.

avetemp = avetemp / multiarray[x].length

I have a counter already for [x] as its being read in from the file but I hoped to not use it here so that I didn't have to manually write out everything.

A sample of what the input text file looks like :

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

Basically the first column is the day of the week and the second is a temperature.

4
  • Use an ArrayList. ArrayList#size() Commented Nov 23, 2013 at 4:17
  • I don't see you putting anything into the array at all. We need to see the code where you are reading from the file and putting stuff into the array. Commented Nov 23, 2013 at 4:18
  • I would go with all the answers here and use an ArrayList or LinkedList, but if you really really have to use a basic array, you can use the Integer boxed type. You can just count all the non-null Integers in the array to get the data length (the array length will still be 500). Commented Nov 23, 2013 at 5:07
  • Yeah okay you're doing this all wrong. Check my edit in a minute. Commented Nov 23, 2013 at 5:34

4 Answers 4

1

Now that I know what your input looks like.

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();
    }
  }
}

Edit: You were adding stuff correctly. My bad.

Sign up to request clarification or add additional context in comments.

1 Comment

Thats great, it does what I need it to. I obviously have a lot more work to do but appreciate the example and comments explaining what the code does.
0

There is not much wrong with this code, but if you initialize the y arrays with length 500, then that is what the length will return, regardless of how many elements were actually filled. If you need that, then initialize the array after you have read the file, or use a java.util.List. If values can't possibly be 0, then you might also iterate all non-0 values, and stop at first 0.

1 Comment

I had hoped that although I had initialized it to 500 the .length would only give me how many elements (?) were added. I will look closer at arraylist as I need to have this work for an unknown amount of entries.
0

Array in java is static ,which means that is has pre-allocated the space you declared,so ,multiarray[y].length will always be 500,no matter how many entries you actually inserted into it.You can use ArrayList or LinkedList instead .Their space are all allocatd dynamically,thus the their length will tell you how many entries they actually contains.

Comments

0

Arrays have a fixed size - you're initializing the second dimension's array to a length of 500. Calling length on that array will always return 500. If you want a more dynamic data structure, consider ArrayList. When you add to it, the value returned by size() will increment.

If you don't want to switch to ArrayList, then you could change the array to a three-dimensional one, with the third dimension having a length of 1. That could be where you maintain the size of your second dimension.

--

I don't know if this is contributing to your error, but you do have a bug in your code. Your while loop at the end tries accessing outside of your temp array:

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

That's looping from 1 to (temp.length + 1) because of your ++x.

Use a for loop instead:

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

1 Comment

I should have commented that area out. I haven't debugged that far yet and am focused on the "for" section about that. I'll edit that code out now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.