2012-02-24 18 views
1

私はこの質問を編集しましたが、プログラムの最後にいくつかのコードを検証するswitch文を記述しようとしました。ユーザーにY/Nを入力して続行するよう依頼しようとしています。彼らがYに入ると、プログラムは再起動するはずです。彼らがNに入ると、プログラムは終了するはずです。 Zに入ると、エラーメッセージが表示され、続行y/nで再度プロンプトが表示されます。 現在、ランダムな文字を入力した場合、データ入力セクションに戻ってきます。その理由はわかりません。ユーザーが入力した文字列を検証する方法は? (Java)

また、私の計算がオフであることに気付きました。私はbigdecimalクラスを使用していないという事実と関係があると仮定しています。現在、私が5.6と入力した場合、それは自動的に560%と仮定します。

私はJavaを使い始めていて、残念なことに苦労しています。誰かが昨夜私を助けてくれたほど親切でした。それは私がハッシュを自分で作り出したからといって、私が喜んで答えてくれたことなしでした。

私はこのクラスでは苦労しているので、何か助けがあれば幸いです。

import java.util.Scanner; 
import java.text.NumberFormat; 

public class LoanCalculator 
{ 
    public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max) //validate double 
    { 
     double d = 0; 
     boolean isValid = false; 
     while(isValid == false) 
     { 
      System.out.println(prompt); //print prompt for double 
      if (sc.hasNextDouble()) 
      { 
       d = sc.nextDouble(); 

       if (d <= min) //if input <= minimum double 
       { 
        System.out.println("Error! Number must be greater than " + min); 
        System.out.println();//print error grater than min double 
       } 
       else if (d >= max) // if input >= maximum double value 
       { 
        System.out.println("Error number must be less than " + max); 
        System.out.println();//print error less than max double value 
       } 
       else 
        isValid = true; //else double is valid 
      } 
      else 
      { 
       System.out.println("Error! Invalid decimal value."); 
       System.out.println(); 
       sc.nextLine(); 
      } 
     } 

     return d; //return double 
    } 
    //validate integer 
    public static int getIntWithinRange(Scanner sc, String prompt, int min, int max) 
    { 
     int i = 0; 
     boolean isValid = false; 
     while(isValid == false) 
     { 
      System.out.println(prompt); //print prompt for integer 
      if (sc.hasNextInt()) 
      { 
       i = sc.nextInt(); 

       if (i <= min) //if input <= minimum integer 
       { 
        System.out.println("Error! Number must be greater than " + min); 
        System.out.println();//print error grater than min integer 
       } 
       else if (i >= max) // if input >= maximum integer value 
       { 
        System.out.println("Error number must be less than " + max); 
        System.out.println();//print error less than max integer value 
       } 
       else 
        isValid = true; //else integer is valid 
      } 
      else 
      { 
       System.out.println("Error! Invalid integer value."); 
       System.out.println(); 
       sc.nextLine(); 
      } 
     } 

     return i; //return integer 
    } 

    public static void main(String[] args) 
    { 
     System.out.println("Welcome to the loan calculator"); //welcome user to loan calculator 
     Scanner sc = new Scanner(System.in); // create new scanner 
     String choice = "y"; //start choice loop 
     while (choice.equalsIgnoreCase("y")) 
     { 
      System.out.println(); 
      System.out.println("DATA ENTRY"); 
      double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0); //get user input for loanAmount 
      //get user input for interestRate 
      double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20); 
      //get user input for years 
      int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100); 
      int months = years * 12; // calculate years to months 
      //calculate monthly payment 
      double monthlyPayment = loanAmount * interestRate/ (1 - 1/Math.pow(1 + interestRate, months)); 
      //import currency instance 
      NumberFormat currency = NumberFormat.getCurrencyInstance(); 
      // import percent instance 
      NumberFormat percent = NumberFormat.getPercentInstance(); 
      percent.setMinimumFractionDigits(1); //set fraction digits for percent 
      System.out.println("RESULST"); //print results 
      //print loanAmount 
      System.out.println("Loan Amount: " + currency.format(loanAmount)); 
      //print interestRate 
      System.out.println("Yearly interest rate: " + percent.format(interestRate)); 
      System.out.println("Number of years: " + years); //print years 
      //print monthlyPayment 
      System.out.println("Monthly payment: " + currency.format(monthlyPayment)); 

      boolean quit = false; 
      do { 
       System.out.println(); 
       System.out.println("Continue? (y/n): "); //prompt user to continue 
       String userinput1 = sc.next(); 

       char choice1 = userinput1.toLowerCase().charAt(0); 
       switch (choice1) { 
        case 'y': 
         break; 
        case 'n': 
         // case n, do something here 
         quit = true; 
         break; 
        case ' ': 
         System.out.println("Error! This entry is required. Try again."); 
         break; 
        default: 
         System.out.println("Error! Entry must be 'y or 'n''"); 
         break; 
       } 
      } while (!quit); 
     } 
    } 
} 
+0

「の範囲内の数値をチェックする私が作成している方法は」:これは本当に多くのではありません異なる。 – Thilo

+0

プロンプトを印刷した後、スキャナを適用する前にユーザー入力を読み取る必要があります。何かが好きです:String line = new BufferedReader(new InputStreamReader(System.in))。readLine();次の行を検証することができます:if( "Y" .equalsIgnoreCase(line)).... –

答えて

2

使用このようなswitch

あなたのコードで
boolean quit = false; 
do{ // change your while by this 

    // your own stuff here 


    // then after all your program stuff 
    boolean choiceIsOK = false; 
    do{ 
    String userinput = sc.next(); 
    char choice = userinput.toLowerCase().charAt(0); 
    switch(choice){ 
    case 'y': 
     // case y, do nothing, you could even remove that case. 
     choiceIsOK = true; 
     break; 
    case 'n': 
     // case n, do something here 
     choiceIsOK = false; 
     quit = true; 
     break; 
    default: 
     // error or warning 
     System.out.println("Type Y or N to respectively continue or quit"); 
     break; 
    } 
    }while(!choiceIsOK); 
}while (!quit); 

、それは次のようになります。

public static void main(String[] args) 
{ 
System.out.println("Welcome to the loan calculator"); //welcome user to loan calculator 
Scanner sc = new Scanner(System.in); // create new scanner 
//String choice = "y"; //start choice loop [no need for that line anymore] 
boolean quit = false; 
do{ 
     System.out.println(); 
     System.out.println("DATA ENTRY"); 
     double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 
       0.0, 1000000.0); //get user input for loanAmount 
     //get user input for interestRate 
     double interestRate = getDoubleWithinRange(sc, 
       "Enter yearly interest rate: ", 0, 20); 
     //get user input for years 
     int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100); 
     int months = years * 12; // calculate years to months 
     //calculate monthly payment 
     double monthlyPayment = loanAmount * interestRate/ 
       (1 - 1/Math.pow(1 + interestRate, months)); 
     //import currency instance 
     NumberFormat currency = NumberFormat.getCurrencyInstance(); 
     // import percent instance 
     NumberFormat percent = NumberFormat.getPercentInstance(); 
     percent.setMinimumFractionDigits(1); //set fraction digits for percent 
     System.out.println("RESULST"); //print results 
     //print loanAmount 
     System.out.println("Loan Amount: " + currency.format(loanAmount)); 
     //print interestRate 
     System.out.println("Yearly interest rate: " + percent.format(interestRate)); 
     System.out.println("Number of years: " + years); //print years 
     //print monthlyPayment 
     System.out.println("Monthly payment: " + currency.format(monthlyPayment)); 


     // then after all your program stuff 
     boolean choiceIsOK = false; 
      do{ 

       System.out.println(); 
       System.out.println("Continue? (y/n): "); //prompt user to continue 
       String userinput1 = sc.next(); 
        char choice1 = userinput1.toLowerCase().charAt(0); 
        switch(choice1){ 
        case 'y': 
         // case y, do nothing, you could even remove that case. 
         choiceIsOK = true; 
         break; 
        case 'n': 
         // case n, do something here 
         choiceIsOK = true; // I fixed this 
         quit = true; 
         break; 
        default: 
         // error or warning 
         System.out.println("Type Y or N to respectively continue or quit"); 
         break; 
        } 
       }while(!choiceIsOK); 

    }while(!quit); 

    }   
} 
+0

私はこのステートメントを試したときに助けなければなりません、継続Y/Nの代わりにプログラムの前の部分にジャンプしました。 –

+0

あなたがまだオンで、私のために探すことができるなら、私はプログラム全体を再掲載しました。私はそれが何かシンプルだと確信していますが、データ入力セクションに戻ってきます。 –

+0

Voilà!ここでは簡単なアプリケーションループがあります。 –

1

使用if声明、

choice =sc.next().toLowerCase(); 
if(choice.equals("y")) 
{ 
    // 
} 
else 
if(choice.equals("n")) 
{ 
    // 
} 
else 
{ 
//invalid input 
} 
1

あなたが条件を使用する必要があり、これらはフォームあなたのブール条件としてString.equals()機能を使用することになり、あなたの場合は

if(someBooleanCondition){ 
    doSomething(); 
} 
else{ 
    doSomethingElse(); 
} 

を持っています。 NOT ==これは文字列で奇妙な結果を与える可能性があるためです。だからあなたはこのようなことをするべきです。そのが繰り返し入力をチェックしますので、このループを持っている

String userInput = sc.next().toLowerCase(); 
if(userInput.equals("y")){ 
//Its yes, do something here 
} 
else if(userInput.equals("n")){ 
//It's no, do something else 
} 
else{ 
    //Handle an invalid entry here 
} 

方法がある:あなたが持っているしたい場合は

while(true) 
String userInput = sc.next().toLowerCase(); 
if(userInput.equals("y")){ 
//Its yes, do something here 
break; 
} 
else if(userInput.equals("n")){ 
//It's no, do something else 
break; 
} 
else{ 
    //Handle an invalid entry here 
} 

これは、彼らがYまたはNを入力するまでのものを入力保つためにユーザーを強制しますそれらは終了するために改行文字を入力することができるか、それをあなたのループに追加することができます。

+0

これを私のelse文の最後に記述すれば、どうすればループするのですか?私はif else文を使用した場合、私は問題があると考えました。例えば私の無効なエントリでは、私はW/Yを続けるように戻って来るようにwoudl。 –

+0

編集された回答。最後の部分は – jozefg

関連する問題