Abhishek Priyankar
Abhishek Priyankar

Reputation: 63

Unable to print 2d Array in Java

I am trying to take input to 2d array and print it .

I don't want to use ArrayList collection of Java Interfaces or any other libraries I am having problem in printing it on the console .The input is working well

import java.lang.*;
import java.util.*;

class Triangle{
    public static int n;
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        int i, j, cases;
        int[][] values = new int[100][100];
        cases = in.nextInt();
        while(cases-- > 0){
            n = in.nextInt();
            int temp;
            for(i=0 ; i<n ; i++){
                for(j=0 ; j<=i ; j++){
                    values[i][j] = in.nextInt();
                }
            }    
        }
        large(values);
    }
    public static void large(int[][] arr){
        for(int i = 0 ; i<n ; i++){
            for(int j=i ; j<i ; j++){
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Upvotes: 1

Views: 163

Answers (2)

GhostCat
GhostCat

Reputation: 140417

Your problems start here:

public static void large(int[][] arr){
    for(int i = 0 ; i<n ; i++){

What makes you think that the last n entered by the user reflects the boundaries of your arrays?

In other words: you defined your array to be of size 100 x 100; and arrays themselves know their size; so you just go for

for(int i=0; i < arr.length; i++) {
  for (int j=0; j < arr[i].length; j++) {

And please note: you should consider to rework your "input" method as well. As of now, that code is highly confusing; looping style is strange; and as said: good protection against going beyond array limits ... looks differently than what you put down!

Upvotes: 2

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

If you want to print all the array you need to start each index with 0, in you code you start your second loop with i, and you forgot to add each entry to the sum

      public static void large(int[][] arr){
    for(int i = 0 ; i<n ; i++){
        for(int j=0 ; j<i ; j++){
            System.out.print(arr[i][j]);
             sum+=arr[i][j];
        }
        System.out.println();
    }
    System.out.println(sum);
   }

Upvotes: 1

Related Questions