gpt4 book ai didi

java - 从存储在数组中的行打印选定的数字

转载 作者:行者123 更新时间:2023-12-02 05:03:25 25 4
gpt4 key购买 nike

我必须写一些接受输入的内容,例如

4 
2 11 1
3 2 1 1
4 4 5 6 2
5 1 1 1 1 2

第一个数字表示后面有多少行,每行的第一个数字表示后面的整数的数量,每行的最后一个数字表示要打印的内容(索引从 1 开始)。之间的数字是数组中存储的内容:

11
2
5
1

这是我到目前为止的想法,这显然是错误的。

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int lines = sc.nextInt();
int size = sc.nextInt();
int[] a = new int[size - 1];

while (lines <= 0) {
lines = sc.nextInt();
}
for (int i = 0; i <= lines; i++) {
a[i] = sc.nextInt();
}
sc.close();
}

我不需要答案;我需要一些指导,因为我迷路了。

最佳答案

看起来最终目标是创建一个 int[][],尽管值得注意的是它可能是一个锯齿状矩阵(不同的行可能有不同的长度)。

如果记住这一点,处理每条输入的操作就会变得更简单。

从那里,您想要根据每行的最后一个元素打印每个数组的第 (i - 1) 元素。一旦你有了矩阵,这很简单,虽然有点奇怪。

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


int lines = sc.nextInt();
int[][] input = new Integer[lines][]; //This is the matrix we are building

for(int i = 0; i < lines; i++){ //For each row of numbers
int size = sc.nextInt(); //Find out how many numbers on this row
input[i] = new int[size]; //Create array of this size for this row
for(int x = 0; x < size; x++){ //For each number on this row
input[i][x] = sc.nextInt(); //Read it into the correct row,col positon
}
}

sc.close();

//Do printing
for(int[] row : input){
int lastElm = row[row.length - 1];
System.out.println(row[lastElm - 1]);
}
}

关于java - 从存储在数组中的行打印选定的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28034832/

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