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)