Himanshu Aggarwal
Himanshu Aggarwal

Reputation: 1809

could not figure out the exception in this code snippet of java

i have tried this code snippet but could not able to figure out the reason for this the exception.

my code is:-

import java.util.*;
class ScannerTest
{
 public static void main(String[]args)
  {
    String csv = "Sue,5,true,3";
    Scanner sc = new Scanner(csv);
    sc.useDelimiter(",");
    int age = sc.nextInt();
    System.out.println(age);
  }
}

Output is:-

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)

i am new to java so please help me out to know the reason for this exception.

Upvotes: 0

Views: 1514

Answers (3)

Reimeus
Reimeus

Reputation: 159754

The scanner is expecting an integer type but the first token is a String - "Sue", To fix, place:

sc.next(); // skip "Sue"

before the call to nextInt() to consume the String token.

Upvotes: 1

tagtraeumer
tagtraeumer

Reputation: 1491

in the javadoc example you can see how it works:

String input = "1 fish 2 fish red fish blue fish";
     Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
     System.out.println(s.nextInt());
     System.out.println(s.nextInt());
     System.out.println(s.next());
     System.out.println(s.next());
     s.close(); 

your first token is a string. if you use next int it expects an integer. you might want to use something like this (under the conditions that you know the structure of the csv and it doesn't change):

public static void main(String[]args)
      {
        String csv = "Sue,5,true,3";
        Scanner sc = new Scanner(csv);
        sc.useDelimiter(",");
        sc.next();
        int age = sc.nextInt();
        System.out.println(age);
      }

or

public static void main(String[] args) {
        String csv = "Sue,5,true,3";
        String ageString = csv.split(",")[1];
        System.out.println(ageString);
    }

...

to parse a string into int:

int age = Integer.parseInt(ageString);

Upvotes: 4

fvu
fvu

Reputation: 32953

The Javadoc of the nextInt method of Scanner states

Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.

As your first token is a String, this is what's going on. As in most cases in CSV's you will know what will be presented, you should read them one by one, and/or use the hasNextInt method and its friends to check whether what you expect is actually there.

Upvotes: 3

Related Questions