0

ユーザー入力を検証しようとしています、cuPerTerm > 12

エラー メッセージが表示されますが、プログラムは続行され、無効な入力を使用して実行されます

package gradplanner;

import java.util.Scanner;

public class GradPlanner {

int cuToComp;
int cuPerTerm;

public static void main(String[] args) {

    final double COST = 2890.00; //flat-rate tuition rate charged per term
    final int MONPERTERM = 6; //number of months per term
    int cuToCompTotal = 0;   
    int numTerm;
    int numMonToComp;
    double tuition;



      //prompt for user to input the number of CUs for each individual course remaining.
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");     
    int cuToComp = in.nextInt();



      //add all CUs from individual courses to find the Total number of CUs left to complete.
    while (cuToComp > 0)
    {
      cuToCompTotal += cuToComp;

      System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
      cuToComp = in.nextInt();
    }

    System.out.println("The total number of CUs left is " + cuToCompTotal);



      //prompt for user to input how many CUs they plan to take per term.
    System.out.print("How many credit units do you intend to take per term? ");
    int cuPerTerm = in.nextInt();

        if (cuPerTerm <12) //validate input - Undergraduate Students Must enroll in a minimum of 12 CUs per term
        {
            System.out.print("Undergraduate Students must enroll in a Minimum of 12 CUs per Term. ");

        }


        //Calculate the number of terms remaining, if a remain is present increase number of terms by 1.   
     numTerm = cuToCompTotal/cuPerTerm;
        if (cuToCompTotal%cuPerTerm > 0)
        {
          numTerm = numTerm + 1;  
        }
     System.out.println("The Number of Terms you have left is " + numTerm + " Terms. ");



       //Calculate the number of Months left to complete
     numMonToComp = numTerm * MONPERTERM;
     System.out.println("Which is " + numMonToComp + " Months. ");



       //calculate the tuition cost based on the number of terms left to complete.
     tuition = numTerm * COST;
     System.out.println("Your Total Tuition Cost is: " + "$" + tuition +" . ");

}
}

12 以上が入力されるまで再質問を続ける必要があります。プログラムを続行します。

4

5 に答える 5

1

簡単な解決策は次のとおりです。

int cuPerTerm = -1; // intialize to an invalid value
while (cuPerTerm < 12) {
    System.out.print("How many credit units do you intend to take per term? ");
    int cuPerTerm = in.nextInt();

    if (cuPerTerm <12) { //validate input - Undergraduate Students Must enroll in a minimum of 12 CUs per term

        System.out.print("Undergraduate Students must enroll in a Minimum of 12 CUs per Term. ");
    }
}
于 2013-10-21T22:07:39.237 に答える