Andrew Andrew - 10 days ago 6
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:
1
2
3
4
5
When I try to say scanner.next it says there is a no element exception.
But I also need to account for a file like this:
Michael
Hannah
Josephus
Ruth
Matthew
So I can't just say nextInt because it could be a string.
How can I check if its integers or strings?
Thanks!
My code:

Scanner sc = new Scanner(f);
int k = 1;
String line = new String(sc.next());
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);
nodes.setNext(last);
return nodes;

Answer

You could use Scanner.next() 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()) {
    s=scn.next();
    try {
       Integer.parseInt(s); 
       //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 = scn.next();
            //handle all as strings 
       }
}
Comments