0

ユーザー入力を必要とするプログラムを作成する必要があるクラスプロジェクトがあり、ユーザー入力を取得して値をメインに返すメソッドを作成したいのですが、何らかの理由で、以下のコードを使用すると次のエラーが発生します。

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

ドキュメントに記載されているように、 ScannerScannernext()メソッドは文字列を返します。nextInt()int を読み取りたい場合に使用します。別の方法として、String を読み取ってから Integer.parseInt() といくつかのエラー チェックを使用することもできます。

于 2013-11-05T01:18:46.063 に答える