2013-10-22 76 views
0

我需要能夠在while循環中按'q'來讓它退出循環。然後,我需要代碼才能顯示旁邊成績的學分。接下來,我必須根據他們的小時數和成績輸入他們的GPA。每次按'q'退出時,程序停止並不顯示任何內容。請幫忙!使用帶循環語句的while循環的GPA計算器。 Java源代碼

package shippingCalc; 
import javax.swing.JOptionPane; 

public class Gpa { 

    public static void main(String[] args) { 

     String input = ""; 
     String let_grade; 
     int credits = 0; 
     double letterGrade = 0; 
     int course = 1; 



     String greeting = "This program will calculate your GPA."; 
     JOptionPane.showMessageDialog(null, greeting,"GPA Calculator",1); 

      while(!input.toUpperCase().equals("Q")) 
      { 
       input = JOptionPane.showInputDialog(null, "Please enter the credits for class " + course); 
       credits = Integer.parseInt(input); 
       course ++; 

        input = JOptionPane.showInputDialog(null,"Please enter your grade for your " +credits + " credit hour class"); 
        let_grade = input.toUpperCase(); 
        char grade = let_grade.charAt(0); 

        letterGrade = 0; 
        switch (grade){ 
        case 'A': letterGrade = 4.00; 
         break; 
        case 'B': letterGrade = 3.00; 
         break; 
        case 'C': letterGrade = 2.00; 
         break; 
        case 'D': letterGrade = 1.00; 
         break; 
        case 'F': letterGrade = 0.00; 
         break; 

      } 

     } 
     JOptionPane.showMessageDialog(null, course++ + "\n\n It Works" + letterGrade); 
    } 
} 
+0

不相關的問題之前插入這行代碼,但你的意思是'情況「d」:letterGrade = 1.00;'和'情況'F':letterGrade = 0.00;'? –

+0

如果你輸入「q」,你應該在這一行上得到一個異常:'credits = Integer.parseInt(input);' – Cruncher

+0

credits = Integer.parseInt(input);是的,我是。如何在while循環中更改測試表達式以在需要時退出? – user2906074

回答

0

我認爲這個問題是,信用是一個int和第二彈出

input = JOptionPane.showInputDialog(null, 
"Please enter the credits for class " + course); 

分配之後無論用戶類型爲int的學分,因此,如果您輸入串Q或Q它會破壞。另外,請記住while循環條件在迭代開始時只被檢查一次,因此它不會知道輸入值直到那個時間

有幾種方法可以修復這個。一個快速簡便的方法是將用戶分配輸入到信用

if(input.equalsIgnoreCase("q")){ 
    continue;//will allow input to be checked immediately before assigning to credits 
}