1

我正在使用 java 并希望使用 Scanner 来获取用户输入然后输出数组。

我创建了一个适用于其中一个的文件和一个单独的文件适用于另一个,但我想询问用户问题并获取自定义数组属性(可变数量的数组、可变行、可变列、变量加法、减法和数组的乘法)

import java.util.Scanner;
import java.io.IOException;

public class ScannerDemoforNetbeans
{

public static void main (String [] args)throws IOException
{
//`enter code here`
System.out.println ("Okay, you got it! How many rows  do you want");
   Scanner rc= new Scanner (System.in);
   public static rows;
   rows= rc.nextInt();
   System.out.println ("How many columns do you want?");
   Scanner c = new Scanner (System.in);
   public static columns;
   columns = c.nextInt();
   System.out.println ("Rows" + rows);
   System.out.println ("Columns:" + columns);


}
   // }   
   // public static void createarray (String [] args)
   // {
    int matWidth = ScannerDemoforNetbeans.columns;
        int matHeight = ScannerDemoforNetbeans.rows;
        int maxCellValue = 70;

                    int [][] mat1 = new int [matHeight][matWidth];
                    int [][] mat2 = new int [matHeight][matWidth];
                    int [][] sum = new int [matHeight][matWidth];

                    for (int i=0; i<matHeight; ++i)
                    {
                        for (int j=0; j<matWidth; ++j)
                        {
                            java.util.Random r = new java.util.Random();
                            mat1 [i][j]= r.nextInt (maxCellValue);
                            mat2 [i][j] = r.nextInt (maxCellValue);
                        }
                    }

                    print2Darray (mat1);
                    System.out.println ();
                    print2Darray (mat2);
                    for (int i=0; i<matHeight; ++i)
                    {
                        for (int j=0; j<matWidth; ++j)
                        {
                            sum [i][j]= mat1 [i][j] + mat2 [i][j];
                        }
                    }
                    System.out.println ();
                    print2Darray (sum);
    }
    public static void print2Darray (int[][]arr)
    {
        for (int [] i : arr)

        {
          for (int j : i)  
          {
              System.out.print (j + " ");
          }
        System.out.println();
        }
    System.out.println ();
    }
}

任何帮助表示赞赏。

4

1 回答 1

0
package araay;
import java.util.Scanner;

public class Araay {

    public static void main(String[] args)
    {

      Scanner a=new Scanner(System.in);
     int i=0;
     int j=0;
     int arr[][]=new int [3][3];
     System.out.println ("Enter the numbers");

     for (i=0;i<=3;i++)
          for(j=0;j<=3;j++)
     arr[i][j]=a.nextInt();>>>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at araay.Araay.main(Araay.java:18)//this error is occur in this code plz solve it



     for (i=0;i<=3;i++)
     for(j=0;j<=3;j++)
      System.out.println("The matrix of array is "+arr[i][j]+"\t");
      System.out.println();
    }


}
于 2013-03-03T12:54:31.817 回答