给定一个排序的整数列表,输出中间的整数。负数表示输入的结尾(负数不是排序列表的一部分)。假设整数的数量始终是奇数。
例如:如果输入是:
2 3 4 8 11 -1
输出是:
中间项:4
任何测试用例的列表值的最大数量不应超过 9。如果超过,则输出“Too much number”。
提示:首先将数据读入数组。然后,根据数组的大小,找到中间的项。
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] userValues = new int[9]; // Set of data specified by the user
int middleItem;
/* Type your code here. */
for(int i=0; i<userValues.length; ++i){
while(userValues[i]>=0){
userValues[i] = scnr.nextInt();
}
}
if(userValues.length>8){
System.out.println("Too many numbers");
}
else{
middleItem = userValues[userValues.length/2];
System.out.println("Middle item: " + middleItem);
}
}
}
到目前为止的主要问题是找到一种方法来扫描少于允许的最大数量的数组项,并在输入负数时停止循环。我删除了使用负整数作为哨兵值的代码,以专注于扫描和接受更少的输入。任何指导将不胜感激。
您可以通过 for 循环逐一读取整数并将它们添加到
List
中,当输入负数时终止。
List<Integer> numbers = new ArrayList<>();
for (int x; (x = scnr.nextInt()) >= 0;)
numbers.add(x);
System.out.println(numbers.get(numbers.size() / 2));
这就是我解决这个问题的方法。我检查了 for 循环开头是否有太多输入。如果 i 大于数组的长度并且输入不是 -1,则会检测到太多数字。
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] userValues = new int[9]; // Set of data specified by the user
int lastValueIndex = 0;
for (int i = 0; i <= userValues.length; i++) {
if (i == 9) {
if (scnr.nextInt() == -1) {
lastValueIndex = i;
break;
}
else {
System.out.println("Too many numbers");
}
return;
}
userValues[i] = scnr.nextInt();
if (userValues[i] == -1) {
lastValueIndex = i;
break;
}
}
System.out.println("Middle item: " + userValues[lastValueIndex / 2]);
}
}