0

I have to write a program that reads in a sequence of integers until 'stop' is entered, store the integers in an array and then display the average of the numbers entered. I'm getting an input mismatch exception when entering 'stop' so it doesn't really work, but I have no idea why. Help would be greatly appreciated.

import java.util.Scanner;

public class 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();
}

}

jacka92
  • 55
  • 1
  • 1
  • 7
  • Your program grabs "stop" and tries to turn it into an int which it cannot do. Maybe you should make use of `Scanner#hasNextInt()`. Also, as a side note, you shouldn't have to make a new scanner every iteration like you do right now. Print the prompt, create a new scanner, print the prompt, create a new scanner, print the prompt, create a new scanner... – takendarkk Sep 02 '14 at 17:39

1 Answers1

0

First int[] array = { n }; just creates an array with 0 as the element in it.

the logic inside it will never execute while (s != "stop");

You want something like this

    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

I recommend you to learn the basics

SparkOn
  • 8,806
  • 4
  • 29
  • 34