2016-10-09 3 views
1

私は、ユーザー入力を検証しようとしています。プログラムが、intではなく、intが9から12の範囲にない場合に、ユーザーにグレードを求める最初の質問にループバックします。このコードを書くのに「より良い」方法がありますか?このユーザーの認証コードをより効率的かつ/または読みやすくする方法はありますか?

do 
    { 
     if (userGrade < 9 || userGrade > 12) 
     { 
      System.out.println("That is not a valid grade!"); 
     } 

      System.out.printf("Grade (9-12): "); 

     while(!enterInfo.hasNextInt()) 
     { 
      System.out.println("That is not a number! Enter in a valid number."); 
      enterInfo.next(); 
     } 
     userGrade = enterInfo.nextInt(); 
    } while (userGrade < 9 || userGrade > 12); 
+0

while条件がdoブロック内で繰り返されています。 – Stavm

+0

何かを読んだ後は、 'enterInfo.nextLine()'を呼び出してバッファから改行を取り除く必要があります。 – Bohemian

+0

答えが有効なときに 'while(true)'ループと 'break;'を使うこともできます。 –

答えて

0

基本的に私はSystem.inを読んでいましたし、何かがある一方で、最初私は整数に変換しようとすると、その整数が正しい範囲内にあるならば、チェック:

package trial; 

import java.util.Scanner; 

public class TestScan { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     try { 
      System.out.println("Please introduce a number:"); 
      Scanner sc = new Scanner(System.in); 
      while(sc.hasNext()){ 
       String input=sc.next(); 
       Integer inputInt; 
       try{ 
        inputInt=Integer.parseInt(input); 
       }catch(Exception e){ 
        System.out.println("You must introduce a number"); 
        continue; 
       } 
       if(inputInt<9 || inputInt>12){ 
        System.out.println("Number must be between 9 and 12 (inclusive)"); 
        continue; 
       } 
       System.out.println("Correct!"); 
      } 
      sc.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 

} 

それは注目に値しますあなたはIDEの外にそれを実行する必要がありますので、理由はSystem.inからの読み取りのため、このプログラムは、お使いのIDEから実行することができます

TestScanフォルダに1-行くと、それをコンパイルします。javac TestScan.java

2.クラスパッチでこのクラスを指定して実行します。例えば。あなたがCにある場合:あなたがベースのカプセル化を使用することができます\ワークスペース\ StackOverflowの\ SRC trial.TestScan

0
if (userGrade < 9 || userGrade > 12) 
    { 
     System.out.println("That is not a valid grade!"); 
    } else { 
    do { 
     System.out.printf("Grade (9-12):   
     "); 

    while(!enterInfo.hasNextInt()) 
    { 
     System.out.println("That is not a number! Enter in a valid number."); 
     enterInfo.next(); 
    } 
    userGrade = enterInfo.nextInt(); 
} while (userGrade < 9 || userGrade > 12)} 
1

コードクリーナーを作るために:> javaの-classpath C:あなたは

Cのようなものを使用することができますクラスと メソッド(カプセル化はOTの主な原因ではありません)。

すべてをメソッドやクラスとして可能な限り小さな部分に分割するので、すべてのメソッドには単純な目的が1つしかありません。このようにして、プログラム全体を読みやすく、理解し、維持しやすくなります。

たとえば、スキャナーオブジェクトがreadInputメソッドのローカルコンテキストで使用されたばかりであることに注目してください。

import java.util.InputMismatchException; 
import java.util.Scanner; 

public class KillerLoop { 

private boolean notReady; 
private int grade; 

public static void main(String[] args) { 

    new KillerLoop(); 

} 

/** 
* the default constructor calls the doStuff method 
* which contains the main loop of the program 
*/ 
public KillerLoop() { 
    this.notReady = true; 
    doStuff(); 
} 

/** 
* the programs main loop 
*/ 
private void doStuff() { 
    while (this.notReady) { 
     int input = this.readInput(); 
     this.verifyInput(input); 
    } 
    System.out.println("Grade " + this.grade + " is a correct grade!"); 
} 

/** 
* verifies a users input 
* if the input is correct, notReady will be set 
* to false so that the programs main loop is left 
* (you could also use an if construct with break for this purpose) 
* @param userGrade the users input 
*/ 
private void verifyInput(int userGrade) { 
    if (userGrade < 9 || userGrade > 12) { 
     System.out.println("That is not a valid grade!\n" + "Grade (9-12): "); 
    } else { 
     this.grade = userGrade; 
     this.notReady = false; 
    } 

} 

/** 
* this method reads input from the command line 
* and returns an integer if successful 
* @return the users input as integer 
*/ 
private int readInput() { 
    Scanner scanner = new Scanner(System.in); 
    System.out.println("enter a grade"); 

    int userGrade = 0; 

    try { 
     userGrade = scanner.nextInt(); 
    } catch (InputMismatchException e) { 
     System.out.println("That is not a number! Enter in a valid number."); 
     this.readInput(); //this recursion might not always be a good idea ;) 
    } 
    return userGrade; 
} 
} 
関連する問題