gpt4 book ai didi

java - 使用扫描仪生成阵列

转载 作者:行者123 更新时间:2023-12-01 04:56:42 25 4
gpt4 key购买 nike

我正在使用java,想要使用扫描仪来获取用户输入,然后输出数组。

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

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

感谢任何帮助。

最佳答案

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


}

关于java - 使用扫描仪生成阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13982147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com