有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java中读取3整数数组以查找中间数和最大数?

如果用户输入[3,5,2]

我该如何编写代码,使3与“a”、5与“b”、2与“c”关联

public static void main(String[] args) {


    int a = input.nextInt();
    int b = input.nextInt();
    int c = input.nextInt();
    int x = 0;
    int t = 0;

    {
        //MIN
        x=a;
        if ((b < x))t=b;
        if ((c < x))x=c;

        //MAX
        t=a;
        if ((b > t)) t=b;
        if ((c > t)) t=c;
    }

    int m = a+b+c-x-t;
    System.out.print(m+t);
}

}

我不希望每个变量都有单独的int输入,而是一个数组


共 (1) 个答案

  1. # 1 楼答案

    这应该行得通:

        Scanner scanner = new Scanner(new File("input.txt"));
        List<Integer> list = new ArrayList<Integer>();
        scanner.nextInt(); // this solution omits number of datasets. we don't really need it
        while (scanner.hasNext()) { // do we have one more line?
            list.clear(); // we need empty list
            for (int i=0;i<3;i++) { // read 3 numbers
                list.add(scanner.nextInt());
            }
            Collections.sort(list);
            Integer max = list.get(2);
            Integer middle = list.get(1);
            System.out.println(max+middle);
        }