1

I am writting a program where the user enters a String input and the program finds the number of words and the number of int numbers. Scanner should close when the user enters "0".

My code

import java.util.Scanner;

public class RunMe
{
public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    String  input = in.nextLine();
    Counter numbers = new Counter();
    Counter words = new Counter();
    Scanner s = new Scanner(input).useDelimiter("\\s");

    while(s.nextInt() != 0)
    {
        if(s.hasNextInt())
        {
            numbers.add();
        }
        else
        {
            words.add();
        }
    }

    s.close();
    in.close();
    System.out.println("Number of numbers : " + numbers.value());
    System.out.println("Number of words : " + words.value());

}
}

and the class Counter

public class Counter
{
    private int value;

    public int add()
    {
        value++;
        return value;
    }
    public int value()
    {
        return value;
    }
}

When I run my program I get the following excepion:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at RunMe.main(RunMe.java:13)
  • 1
    Can you please include a sample input in your post as well?. – Pavan Dittakavi Nov 01 '15 at 15:10
  • 1
    s.nextInt() will only read in a number and not a string(word). When you try to enter a word s.nextInt() will give you InputMismatchException because it's expecting a number. – Yan Nov 01 '15 at 15:12

2 Answers2

3

Change the condition of your main loop to check if there is something to read and use a break if the numeral is equals to 0.


Solution

while(s.hasNext())
{
    if(s.hasNextInt())
    {
        if (s.nextInt() == 0) break;
        numbers.add();
    }
    else
    {
        s.next();
        words.add();
    }
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
0

With Scanner the console input must be feed using "enter". To avoid this, some other native library would be required, such as JLine. There are other options in this similar question.

Community
  • 1
  • 1
Tsung-Ting Kuo
  • 1,171
  • 6
  • 16
  • 21