Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中,需要程序搜索nextInt,但如果遇到';这不是整数_Java_Loops_Int - Fatal编程技术网

在Java中,需要程序搜索nextInt,但如果遇到';这不是整数

在Java中,需要程序搜索nextInt,但如果遇到';这不是整数,java,loops,int,Java,Loops,Int,这是一段相关的代码 while(fileDoc.hasNextInt()) { int number=fileDoc.nextInt(); 如果(数量>=最大值) 最大值=数量; 如果(number您应该首先尝试将每一行作为字符串读取,然后处理异常,将字符串解析为int。您可以尝试以下操作: try (BufferedReader br = new BufferedReader(new FileReader("file_name.txt")) { String line = null;

这是一段相关的代码

while(fileDoc.hasNextInt())
{
int number=fileDoc.nextInt();
如果(数量>=最大值)
最大值=数量;

如果(number您应该首先尝试将每一行作为
字符串读取,然后处理
异常
,将
字符串
解析为
int
。您可以尝试以下操作:

try (BufferedReader br = new BufferedReader(new FileReader("file_name.txt")) {
    String line = null;
    while ((line = br.readLine()) != null) {
        try {
            int value = Integer.parseInt(line);
            // your logic here
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
使用
Scanner
next()
方法跳过无效的令牌:

while (fileDoc.hasNext()) {
  if (fileDoc.hasNextInt()) {
    int number = fileDoc.nextInt();
    /* Do whatever... */
  } else {
    fileDoc.next();
  }
}
while (fileDoc.hasNext()) {
  if (fileDoc.hasNextInt()) {
    int number = fileDoc.nextInt();
    /* Do whatever... */
  } else {
    fileDoc.next();
  }
}