0

我必须编写一个程序,读取整数序列,直到输入“停止”,将整数存储在数组中,然后显示输入数字的平均值。输入“停止”时出现输入不匹配异常,因此它实际上不起作用,但我不知道为什么。帮助将不胜感激。

导入 java.util.Scanner;

公共类 MeanUsingList {

public void mean() {

    String s;
    int n = 0;
    int i = 1;
    int[] array = { n };

    do {
        System.out.println("Enter an integer");
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        s = in.nextLine();

    } while (s != "stop");
    {
        System.out.println("Enter an integer");
        Scanner in2 = new Scanner(System.in);
        int x = in2.nextInt();
        array[i] = x;
        i++;
    }

    int av = 0;

    for (int y = 0; y < array.length; y++) {
        av += array[y];
    }

    System.out.println(av);

}

public static void main(String[] args) {
    MeanUsingList obj = new MeanUsingList();
    obj.mean();
}

}

4

1 回答 1

0

首先int[] array = { n };创建一个以 0 为元素的数组。

它里面的逻辑永远不会执行while (s != "stop");

你想要这样的东西

    List list = new ArrayList();
    //instead of array used arraylist because of dynamic size

    do {
        System.out.println("Enter an integer");
        Scanner in = new Scanner(System.in);
        n = in.nextInt(); //get the input
        list.add(n);      // add to the list
        Scanner ina = new Scanner(System.in); // need new scanner object
        s = ina.nextLine(); //ask if want to stop

    } while (!s.equals("stop")); // if input matches stop exit the loop

    System.out.println(list); // print the list

我建议你学习基础知识

于 2014-09-02T17:48:05.093 回答