Andrew Andrew - 8 months ago 62
Java Question

Java: How to check with a scanner to see if a file contains integers or words?

I need to store a text file into a linked list. I am given a text file like:
When I try to say it says there is a no element exception.
But I also need to account for a file like this:
So I can't just say nextInt because it could be a string.
How can I check if its integers or strings?
My code:

Scanner sc = new Scanner(f);
int k = 1;
String line = new String(;
ListNode nodes = new ListNode(n, null);
while(k < n - 1)
line = sc.nextLine();
nodes.setNext(new ListNode(n, null));
line = sc.nextLine();
ListNode last = new ListNode(n, null);
return nodes;

Answer Source

You could use for all tokens, then simply do Integer.parseInt() for tokens with integers. Here is an example:

File f = new File("myfile.txt");
Scanner scn = new Scanner(f);
String s = ""; 
while(scn.hasNext()) {;
    try {
       //if the code made it to this line, s is an int, handle at as such 
    } catch(NumberFormatException e) {
       //s is a string, handle it as such

Just a word of advice, hasNext() will be true even if the next token is an integer. As such, you can't use hasNext() to determine if the file is composed of Ints or Strings. However, if you know in advanced that the file is of one type (no mixed cases), the following would also work:

if(scn.hasNextInt()) { //if true, you know that this file is ints
       while(scn.hasNextInt()) {
            int i = scn.nextInt(); //handle all as ints
} else { //otherwise the file is strings
       while(scn.hasNext()) {
             String s =;
            //handle all as strings