简体   繁体   English

无法在Java中打印2d数组

[英]Unable to print 2d Array in Java

I am trying to take input to 2d array and print it . 我正在尝试输入2d数组并打印它。

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 我不想使用Java接口的ArrayList集合或我在控制台上打印时遇到问题的任何其他库。输入运行良好

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

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? 是什么让您认为用户输入的最后一个n反映了数组的边界?

In other words: you defined your array to be of size 100 x 100; 换句话说:您将阵列定义为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! 并且如上所述:防止超出阵列限制的良好保护......看起来与你放下的不同!

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 如果你想要打印所有数组,你需要用0开始每个索引,在你的代码中你用i开始你的第二个循环,你忘了将每个条目添加到总和

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM