-3

So I want to read a file, that contains numbers separated by spaces. For example, the file "try.txt" content is:

1 2 3
4 5 6
7 8 9

I know how to read this numbers and store them in an array with a Scanner, and two nested for loops.Ignore any possible sintax errors here. It would look like:

int i,j;
Scanner sc
for(i=0;i<array.length;i++){
   for(j=0;j<array[i].length;j++){
      array[i][j]=sc.nextInt();
   }
}

So my question is, how can I check that what I am reading is actually an integer? What happens if nextInt() finds a letter, or another ASCII symbol?

Thank you.

AliAs
  • 93
  • 1
  • 1
  • 10
  • 3
    It would throw an exception. Try it out. – SMA Oct 06 '17 at 17:17
  • This documentation from Oracle on [Scanner.nextInt()](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextInt--) might be useful. [Edit] your question if you have questions from there. Oracle is a major Java vendor so they provide good documentation. – Tom Blodget Oct 06 '17 at 19:08

2 Answers2

0

Try this code

if (obj instanceof Integer) 
{
    // is a integer
} 
else 
{
   // is not
}
Pritesh Patel
  • 684
  • 14
  • 29
0

At the end, I solved this problem using InputMissmatchException. Here is an example:

Scanner sc = new Scanner(System.in);
try{
    int a = sc.nextInt();
}catch(java.util.InputMismatchException e) {
        System.out.println("Invalid file content");
}
AliAs
  • 93
  • 1
  • 1
  • 10