0

I've the below Java program.

package Arrays;

import java.util.Scanner;

public class Arrays {
    public static void main(String[] args) {
        final int size = 5; // Size of the input Array

        Scanner input = new Scanner(System.in);
        while (!input.equals("q")) {
            System.out.println("Enter the 5 number you want to be stored in an array");

            // get the input of array from the user
            int a[] = new int[size];
            for (int i = 0; i < a.length; i++) {
                a[i] = input.nextInt();
            }

            /* Methods */
            System.out.println("\n");
            displayArray(a); // to display the numbers entered in Array
            System.out.println("\n");
            sumOfArray(a);// To print the sum of Array
            System.out.println("\n");
            productOfArray(a);// to print the product of Array
            System.out.println("\n");
            smallAndLargeOfArray(a);// to print the Max and Min number in Array
            System.out.println("\n");
            averageOfArray(a);// to print the average of Array
            System.out.println("\n");
        }
        input.close();
    }

    private static void displayArray(int arr[]) {
        System.out.print("The numbers you have inserted are ");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
            if (i < arr.length - 1) {
                System.out.print(", ");
            }
        }

    }

    private static void sumOfArray(int[] arr) {
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        System.out.print("Sum of array is " + sum);

    }

    private static void productOfArray(int[] arr) {
        int prod = 1;
        for (int i = 0; i < arr.length; i++) {
            prod *= arr[i];
        }
        System.out.print("Product of array is " + prod);
    }

    private static void smallAndLargeOfArray(int arr[]) {
        int minimim = Integer.MAX_VALUE;
        int maximum = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            if (minimim > arr[i]) {
                minimim = arr[i];
            }
            if (maximum < arr[i]) {
                maximum = arr[i];
            }
        }
        System.out.print("Minimum and Maximum numbers in array are " + minimim
                + " and " + maximum);

    }

    private static void averageOfArray(int arr[]) {
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        double avg = sum / 5;
        System.out.print("Average of array is " + avg);

    }

}

here i was trying to continue the program till the user enters q, but here when i enter q it is throwing the below error.

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Arrays.Arrays.main(Arrays.java:16)

please let me know where am i going wrong and how can i fix this.

Thanks

user3872094
  • 2,853
  • 4
  • 23
  • 50

5 Answers5

2

You should do it as , because you are comparing your Scanner object

String inputName=""
Scanner input = new Scanner(System.in);
inputName= in.nextLine();
        while (!inputName.equals("q")) {..}

as scanner object is not equal to "q" (which is a string), the while loop runs continuously. Then the scanner waits for an Integer, but it takes a character. So the scanner throws the exception (saying that the input cannot be converted into integer value)

Read:

Community
  • 1
  • 1
Santhosh
  • 8,045
  • 2
  • 26
  • 54
1

The exception is thrown by the line:

a[i] = input.nextInt();

When you input a 'q', the next token cannot be cast to an int, so get an InputMismatchException. You should check if the next token is an int by using the hasNextInt() method.

Additionally, your condition !input.equals("q") does not make sense. Here, you check if the Scanner object is equal to the string "q". What you want to do is check whether the next token of the Scanner object is equal to the string "q":

boolean cont = true;
while (cont) {
    System.out.println("Enter the 5 numbers you want to be stored in an array");

    // get the input of array from the user
    int a[] = new int[size];
    for (int i = 0; i < a.length; i++) {
        if (input.hasNextInt()) {
            a[i] = input.nextInt();
        }
        else {
            String token = input.next();
            if ("q".equals(token)) {
                cont = false;
                break;
            }
            i--; // move back to the last position
        }
    }

    ...
}
Hoopje
  • 11,820
  • 6
  • 29
  • 47
1

Currently you are trying to compare an object of type String with an object of type Scanner. The result is always false, you enter the while loop and ask for nextInt() which causes a type mismatch because the next token is "q".

You should use input.findInLine() with a regular expression to look at the next token without consuming it and checking if it satisfies your breakout condition.

while(input.hasNextLine() && !input.findInLine("^q$")){
  //...
}

Read:

EDIT: Eddited to use findInLine which does not consume tokens.

Community
  • 1
  • 1
Dennis
  • 480
  • 5
  • 16
  • but here i'm supposed enter only 5 numbers but it is giving me an option to enter 6th(The first is ignored). – user3872094 Nov 26 '14 at 10:30
  • You are right. I edited my answer. The method `findInLine` only looks at the input and does not consume it. The passed regular expression represents the letter _q_ as the first and last letter or a line. Check out the [Documentation](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html) of the Scanner class. – Dennis Nov 26 '14 at 12:14
1

Use the Sysout outside the while loop and change your condition in while loop.

 System.out.println("Enter the 5 number you want to be stored in an array");
        Scanner input = new Scanner(System.in);
        while (!input.next().equals("q")) {
            System.out.println("Enter the 5 number you want to be stored in an array");
Navish Sharma
  • 223
  • 2
  • 11
0

You use nextInt() which only expected int values. Change it to next() and cast the value to an int if it is not q

Jens
  • 60,806
  • 15
  • 81
  • 95