java - hasNextInt() 扫描并未停止

标签 java java.util.scanner

这段代码没问题并且运行良好。

public static void main(String[] args) {
    String [] keywords={"auto","break","case","char","const","continue","default",
            "do","double","else","enum","extern","float","for","goto","if","int",
            "long","register","return","short","signed","sizeof","static","struct",
            "switch","typedef","union","unsigned","void","volatile","while" };
    Scanner sn = new Scanner (System.in);
     if(Arrays.asList(keywords).contains(sn.next())) {
            System.out.println("This is a KEYWORD");
        }

但是当我添加这个

else if(sn.hasNextInt()){
         System.out.println("This is an INTEGER");
     }

然后运行,我的输入扫描仪没有停止,为此,我没有得到任何结果。 为什么会发生这种情况?

请给我一个带有描述的解决方案。预先感谢您。

最佳答案

import java.util.Arrays;
import java.util.Scanner;


public class jh {

    public static void main(String[] args) {
        String [] keywords={"auto","break","case","char","const","continue","default",
                "do","double","else","enum","extern","float","for","goto","if","int",
                "long","register","return","short","signed","sizeof","static","struct",
                "switch","typedef","union","unsigned","void","volatile","while" };
        Scanner sn = new Scanner (System.in);
        /* get the value from scanner.. do not scan a single input twice.
         In your code in line Arrays.asList(keywords).contains(sn.next())) {, you have 
         already got the input once. If you had tried entering another integer after that and you
         should have got the This is an INTEGER
        */
        String string = sn.next();
        Integer someInt = null;
        try{//see if the input was an integer 
         someInt= Integer.parseInt(string);
        }catch(NumberFormatException e){System.out.println(e);}

         if(Arrays.asList(keywords).contains(string)) {
                System.out.println("This is a KEYWORD");
            }
         else if(someInt!=null){
             System.out.println("This is an INTEGER");
         }

}
}

关于java - hasNextInt() 扫描并未停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19150880/

相关文章:

java - '线程 "main"java.util.NoSuchElementException : No line found' When iterating through a loop reading a file 中出现异常

java - 如何删除十六进制格式字符串的一些中间部分以获得新字符串?

java - Spark - Datediff 几个月?

java - 使用扫描仪读取多个位

java - 扫描仪类的 hasNext() 无限循环

java - 扫描仪无法正常工作

java - @MockBean 似乎重新运行上下文创建并在 Migrate.sql 之后失败

java - 为什么要在返回之前将 volatile 分配给局部变量

java - 如何获取默认的 WebApplicationContext?

java - Scanner 类是否将整个文件一次加载到内存中?