[英]Printing a selected number from lines stored in an array
我必须写一些需要输入的东西,例如
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)th
元素。 一旦有了矩阵,这很简单,如果有点怪异的话。
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]);
}
}
我会尝试以下方法:
将文档分成几行,另存为字符串
忽略第1行,也许您可以使用它来交叉检查行的总数?
在行上使用.split(“ \\ s +”),然后将结果转换为整数
从每行中取出最后一个数字(我们叫数字i),然后获取数组的第i个元素
这有道理吗? 我有一个问题,输入文件是否有换行符,还是连续的数字流?
您可能只需执行以下操作:
首先,阅读第一行:
int numberOfLines = Integer.parseInt(sc.nextLine());
然后使用给定的整数创建一个for
循环,以循环以下行:
for (int i = 0; i < numberOfLines; i++) { ... }
然后,在for
循环中,采用每一行:
String line = sc.nextLine();
然后,将行分成几部分,并以空格作为定界符:
String[] parts = line.split(" ");
parts
数组的最后一个索引必须被打印。
int index = parts[parts.length - 1]; int numberToPrint = parts[index]; System.out.println(numberToPrint);
如您所见,您不需要第一个元素来检查给定数字序列的长度。 如果用空格分隔线,则可以使用array属性length
调用最后一个元素。
PS:如果用户输入格式错误,则可能会引发ArrayIndexOutOfBoundsException
。 您可以抓住它并指责用户是愚蠢的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.