可以用循环,然后以输入一个特定的符号来结束输入,用集合来存放输入的数字。代码例子如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Listlist = new ArrayList ();
int temp = 0;
while(true){
System.out.println("输入一个数,输入-1结束:");
temp = sc.nextInt();
if(temp != -1){
list.add(temp);
}else {
System.out.println("输入结束");
break;
}
}
// 输出集合
System.out.println("你所输入的数为:");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
import java.util.Scanner;
public class Demo {
public static void main(String[] agrs) {
System.out.println("请输入需要统计成绩的数量:");
Scanner sc=new Scanner(System.in);
评分(sc.nextInt());
sc.close();
}
public static void 评分(int b)
{
Scanner sc = new Scanner(System.in);
System.out.println("请输入要计算的成绩:");
int a[]=new int[b];
int i;
for (i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
try{
int sum = 0;
int max = a[0];
int min = a[0];
for (i = 0; i < a.length; i++) {
sum += a[i];
}
for (i = 1; i < a.length; i++) {
if (max < a[i])
max = a[i];
}
for (i = 1; i < a.length; i++) {
if (min > a[i])
min = a[i];
}
double avg = (sum - max - min) / (b-2)*1.0;
System.out.println("分数是:" + avg);
}catch(Exception e)
{
System.out.println("未知错误");
}
sc.close();
}
}
其实你也可以考虑用不定长参数来写
import java.util.Scanner;
class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("输入n:");
int n = in.nextInt() - 2;
int max = in.nextInt();
int min = in.nextInt();
int sum = 0;
int temp = n;
sum += max + min;
while (temp-- != 0) {
System.out.println("输入score:");
int score = in.nextInt();
sum += score;
if (score > max)
max = score;
if (score < min)
min = score;
}
System.out.println("分数是:" + (sum - max - min) / n * 1.0);
}
}
输入不确定的数字就应该让最后一个输入的是一个判定字符,就是说输入某个字符结束,字符之前的是你需要的分数。
规定一个结束符,比如接收到“”/0“就结束接受