简体   繁体   English

如何确定我从文件中读取的内容? 爪哇

[英]How can I determine what I read from a file? Java

So I want to read a file, that contains numbers separated by spaces.所以我想读取一个文件,其中包含由空格分隔的数字。 For example, the file "try.txt" content is:例如文件“try.txt”的内容是:

1 2 3 1 2 3
4 5 6 4 5 6
7 8 9 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.我知道如何读取这些数字并将它们存储在一个带有扫描仪和两个嵌套 for 循环的数组中。在这里忽略任何可能的语法错误。 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?如果 nextInt() 找到一个字母或另一个 ASCII 符号会发生什么?

Thank you.谢谢你。

Try this code试试这个代码

if (obj instanceof Integer) 
{
    // is a integer
} 
else 
{
   // is not
}

At the end, I solved this problem using InputMissmatchException.最后,我使用 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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM