0

我有一个类项目,我需要创建一个需要用户输入的程序,我想创建一个获取用户输入并将值返回给 main 的方法,由于某种原因,当我使用下面的代码时出现以下错误,

Names.java:40:错误:不兼容的类型 userInput = kb.next(); ^ 必需:int 找到:字符串

   public static void main(String[] arg)  
               throws FileNotFoundException{  
      Scanner kb = new Scanner(System.in);  
      Scanner fileInput = new Scanner(new File("names.txt"));  
      System.out.println("This program allows you to search through the");  
      System.out.println("data from the Social Security Administration");  
      System.out.println("name popularity since 1900.");  
      int userInput;  
      do{  
         userInput = getInput(kb);  
         if(userInput == 1)  
            namePopularity();  
         if(userInput == 2)  
            nameCompare();  
         if(userInput == 3)  
            nameRank();  
      }while(userInput == 4);  
   }  

   //Gets the user input  
   public static int getInput(Scanner kb){  
      int userInput;  
      do{  
         System.out.println("Choose a task number from the following:");  
         System.out.println("1-See histogram of a name's popularity");  
         System.out.println("2-Compare two names in a specific decade");  
         System.out.println("3-Show what name had a specific rank for a certain decade");  
         System.out.println("4-Exit Program");  
         userInput = kb.next();  
         }while(!userInput.hasNextInt());  
      return userInput;  
   }

我尝试将其分解为一个更简单的版本,如下所示,但我一直收到该错误消息,我不知道为什么它将它作为字符串而不是扫描仪读取,有人可以帮助我吗,直到我尝试使用扫描仪用不同的方法。

   public static void main(String[] arg)  
            throws FileNotFoundException{  
      Scanner kb = new Scanner(System.in);  
      Scanner fileInput = new Scanner(new File("names.txt"));  
      int userInput;  

      System.out.println(getInput(kb));  
   }  
   public static int getInput(Scanner kb){  
      int userInput;  
      System.out.println("write something");  
         userInput = kb.next();  
      return userInput;  
   }  
4

1 回答 1

0

文档Scanner所述next(),Scanner 方法返回一个字符串。如果nextInt()要读取 int,则要使用。另一种方法是读取一个字符串,然后使用 Integer.parseInt() 和一些错误检查。

于 2013-11-05T01:18:46.063 回答