2017-02-05 8 views
0

入力した数字が偶数か偶数かをユーザーに通知します。私は入力検証に助けが必要です。私が必要とする確認は、ユーザーが何も入力することができないということです。 tryとcatchメソッドなしで検証を実行しようとしています。入力の検証はどのように行いますか?

import java.util.Scanner; 
    public class oddoreven { 
     public static void main (String [] args) { 
     Scanner input = new Scanner (System.in); 

     //declaractions 
     int num; 

     //while loop 
     do{ 
     System.out.println("PLease enter a number to see whether it is even or odd. To end tyype in -99."); 
     num = input.nextInt(); 

     // input valid 


     }while(num != -99); // loop ends 

// begins the method 
     public static void is_odd_or_even_number(int number){ 
     int rem = number%2; 


     \ 

答えて

1

あなたは、次の入力がintであるかどうかを判断するためにScanner.hasNextInt()を呼び出して(と何かを消費する)ことができます。また、入力が-99(または99)の場合は99のコードがテストされますが、プロンプトには-99と表示されますが、無限ループおよびbreakを作成することがあります。最後に、メソッドを呼び出す必要があります。何かのように、

public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    int num; 
    do { 
     System.out.println("Please enter a number to see whether it is " 
       + "even or odd. To end type in -99."); 
     if (input.hasNextInt()) { 
      num = input.nextInt(); 
      if (num != -99) { // <-- directions say -99. 
       is_odd_or_even_number(num); 
      } else { 
       break; 
      } 
     } else { 
      System.out.printf("%s is not a valid int.%n", input.nextLine()); 
     } 
    } while (true); 
} 
0

あなたは

num.matches("^[0-9]*$") // return true if all characters are digits 

num.matches("[0-9]+") // return true if all characters are digits 

または

、ユーザーが入力した文字列のすべての文字が数字であるかどうかをチェックするために regexを使用することができますが、それはあなたを変更する前に、 num = input.nextint()~ num = nextLine()とし、 numStringとする。これをやらないと、必要なときにユーザーの入力を検証する必要はありません。

+0

'num'はポスト内の' int'です。 –

+0

@ElliottFrisch私はそれを無視しました。OPが妥当性検査について質問しているのであれば、OPはStringとして入力を受け取るでしょう。とりあえずありがとう。 –

0

Scanner.nextLine()を使用して文字列入力を取得できます。文字をループして、すべて数字であることを確認します。 (負でない整数のみを仮定)

string rawInput = input.nextLine(); 
boolean validInput = true; 
for (char c : rawInput) { 
     if (!Character.isDigit(c)) { 
      validInput = false; 
      break; 
     } 
} 

if (validInput) { 
    int num == Integer.parseInt(rawInput); 
    // proceed as normal 
} 
else { 
    // invalid input, print out error message 
} 
関連する問題