我的最终输出应该是:
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");
}
}
}
答案 0 :(得分:1)
正如我所看到的,您在Scanner
方法中使用了两个(System.in)
来源main()
...
Scanner sc = new Scanner(System.in);
Scanner rows = new Scanner(System.in);
它可能会抛出异常,所以当您使用具有相同来源的其他Scanner
时,您应首先关闭sc.close();
,即Scanner
。