コードクリーナーを作るために:> 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;
}
}
while条件がdoブロック内で繰り返されています。 – Stavm
何かを読んだ後は、 'enterInfo.nextLine()'を呼び出してバッファから改行を取り除く必要があります。 – Bohemian
答えが有効なときに 'while(true)'ループと 'break;'を使うこともできます。 –