我的最终输出应该是这样的:
How many rows are in the jagged array? 4
Enter a row, separated by spaces: 9 2 14 5 8
Enter a row, separated by spaces: 3
Enter a row, separated by spaces: 15 23
Enter a row, separated by spaces: 9 8 7 6 5 4 3
After the funky operation, the resulting array is:
9 4 42 20 40
6
45 92
36 40 42 42 40 36 30
但我不断收到错误:
Exception in thread "main" java.util.NoSuchElementException: No line found
at ScannerHacked.nextLine(ScannerHacked.java:1525)
at jagged.main(jagged.java:14)
这是我的代码:
import java.util.Scanner;
public class jagged {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many rows are in the jagged array? ");
int row = sc.nextInt();
int[][] jaggedArray = new int[row][];
for(int i = 0; i < row; i++)
{ Scanner rows = new Scanner(System.in);
System.out.print("Enter a row, separated by spaces: ");
String arraystring = rows.nextLine();
String []a = arraystring.split(" ");
jaggedArray[i] = new int[a.length];
for(int j = 0; j < jaggedArray[i].length; j++)
{
int y = Integer.parseInt(a[j]);
jaggedArray[i][j] = y;
}
}
System.out.println("After the funky operation, the resulting array is:");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < jaggedArray[i].length; j++)
{
if(jaggedArray[i][j] > 9)
System.out.print(" "+(jaggedArray[i][j]*(i+j+1)) + "");
else
System.out.print(" "+(jaggedArray[i][j]*(i+j+1)) + "");
}
System.out.print("\n");
}
}
}
最佳答案
正如我所看到的,您在 main()
方法中使用了两个具有相同源 (System.in)
的 Scanner
。 .
Scanner sc = new Scanner(System.in);
Scanner rows = new Scanner(System.in);
它可能会抛出异常,因此当您要使用另一个 Scanner
时,您应该先关闭 Scanner
即 sc.close();
相同来源。
关于java - java中的锯齿状数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21594635/