javaarraysuser-inputragged

In java how to make the user enter number of columns in a ragged array but for each row the number of columns should be different


In java I want to create and print a ragged array , The first thing the user must enter the number of rows and then in each row the user will have to enter the number columns and then put whatever number he wants in each column until he reaches to the number that he entered for each row , For example

4 11 22 33 44
2 51 8
6 92 1 3 5 3 99

in the first row the user entered 4 so he could type four numbers

in the second row the user entered 2 so he could type two numbers

in the third row the user entered 6 so he could type four numbers

after that it should print the number that the user entered for each row and whatever he typed in (it should print the example above)

but for some reason using my code

int rows , col, m=0 , z=0 ;

System.out.println("enter number of rows");
rows=input.nextInt();
        
while(z<rows){
System.out.println("in each row enter number of coloms and then enter whatever number you want in there");
col=input.nextInt();
z++;
for(int i =0 ; i<col ; i++) {
m=input.nextInt();}
}
            
int [][] test1 = new int [rows][m];

for(int i =0 ; i<test1.length ; i++) {
for( int j =0 ; j<test1[i].length ; j++)
System.out.print(test1[i][j]+ " ");
System.out.println();}      


all of the output is zeros but the number of rows that the user entered the first thing is correct so I don't have a problem with that

So instead of having an output like this

enter number of rows
3
in each row enter number of coloms and then enter whatever number you want in there
4 11 22 33 44 // for example the user will enter these numbers and it will be printed the way he typed it
2 51 8
6 92 1 3 5 3 99

but I get this output

enter number of rows
3
4 11 22 33 44  // if the user have entered these numbers it will print all of the array zeros depending on the first number in the last row 
2 51 8
6 92 1 3 5 3 99

//  this is what I get
0 0 0 0 0 0 
0 0 0 0 0 0 
0 0 0 0 0 0 

I have been searching to find a solution all the day but I didn't find anything , Any one knows how to solve this problem?

sorry for making you read all that


Solution

  • Solved by using ArrayList instead of the int "array":

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("How many rows?");
        int rowsSize = input.nextInt();
        List<List<Integer>> rows = new ArrayList<>();
        for (int i = 0; i < rowsSize; i++) {
            System.out.println("How many columns?");
            int colSize = input.nextInt();
            List<Integer> cols = new ArrayList<>();
            for (int j = 0; j < colSize; j++) {
                System.out.println("Write a number");
                cols.add(input.nextInt());
            }
            rows.add(cols);
        }
        for (List<Integer> row : rows) {
            for (Integer number : row) {
                System.out.print(number);
            }
            System.out.println("");
        }
    }
    

    As Alex mentioned, array is not suitable for this kind of dynamic re-sizing. Most of the times ArrayList should be preferred instead of array, unless memory/speed is very critical.

    EDIT: Wrote a solution for your problem by using a 2d array, but my advice is to prefer List: public class StackOverflowQuestion {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("How many classes?");
        int numberOfClasses = input.nextInt();
        int largestNumberOfMarksInAClass = numberOfClasses;
        int[][] classesAndMarks = new int[numberOfClasses][largestNumberOfMarksInAClass];
        for (int i = 0; i < numberOfClasses; i++) {
            System.out.println("How many marks in class  " + (i + 1) + "?");
            int numberOfMarks = input.nextInt();
            if (numberOfMarks > largestNumberOfMarksInAClass) { //If the new class has an higher number of marks,
                largestNumberOfMarksInAClass = numberOfMarks;   //we have to increase the size of the 2d array
                classesAndMarks = getResizedArray(numberOfClasses, largestNumberOfMarksInAClass, classesAndMarks);
            }
            for (int j = 0; j < numberOfMarks; j++) {
                System.out.println("Please write a mark");
                classesAndMarks[i][j] = input.nextInt();
            }
        }
    
        int highestAverageIndex = 0;
        double[] averageMarks = averageAllClassesMarks(classesAndMarks);
        System.out.println("Class average");
        for (int i = 0; i < averageMarks.length; i++) {
            System.out.println((i + 1) + " " + averageMarks[i]);
            if (averageMarks[i] > averageMarks[highestAverageIndex]) {
                highestAverageIndex = i;
            }
        }
        System.out.println("The highest average is " + averageMarks[highestAverageIndex] +
                " and it is for class " + (highestAverageIndex + 1));
    }
    
    private static int[][] getResizedArray(int numberOfClasses, int largestNumberOfMarksInAClass, int[][] classesAndMarks) {
        int[][] resizedArray = new int[numberOfClasses][largestNumberOfMarksInAClass];
        for (int i = 0; i < classesAndMarks.length; i++) {
            int[] mark = classesAndMarks[i];
            for (int j = 0; j < mark.length; j++) {
                resizedArray[i][j] = mark[j];
            }
        }
        return resizedArray;
    }
    
    private static double[] averageAllClassesMarks(int[][] classesAndMarks) {
        double[] averageAllClasses = new double[classesAndMarks.length];
        for (int i = 0; i < classesAndMarks.length; i++) {
            averageAllClasses[i] = averageClassMarks(classesAndMarks[i]);
        }
        return averageAllClasses;
    }
    
    private static double averageClassMarks(int[] marks) {
        double sum = 0;
        double numberOfMarks = 0;
        for (int mark : marks) {
            sum += mark;
            if (mark != 0) {
                numberOfMarks++;
            }
    
        }
        return Math.round((sum / numberOfMarks) * 100.0) / 100.0;
    }
    

    }