2013-11-05 53 views
0

我有一个类项目,我需要创建一个需要用户输入的程序,我想创建一个获取用户输入并返回值为main的方法,出于某种原因我使用下面的代码时出现以下错误,扫描仪以不同的方式读取字符串

Names.java:40:错误:不兼容的类型 userInput = kb.next(); ^ 要求:整数 发现:字符串

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; 
    } 

回答

0

作为在Scanner扫描器的next()方法返回字符串的documentation说明。如果你想读int,你想使用nextInt()。另一种方法是读取一个字符串,然后使用Integer.parseInt()和一些错误检查。

+0

非常感谢你 –