2015-10-18 615 views
2

我不確定如何創建使用小數精度的switch語句,因爲switch語句與double日期類型不兼容。switch語句;小數精度

double grade = input.nextDouble(); //read grade 

    while (grade !=-1) 
    { 
     total += grade; // add grade total 
     ++gradeCounter; // increment number of grades 

     // increment appropriate letter-grade counter 
     switch (grade/1) 
     { 
      case 92.5: // grade was between 90 
      case 100: // and 100, inclusive 
       ++aCount; 
       break; // exits Switch 

是我遇到的麻煩的代碼的特定部分,但我不知道我改變與開關。

它使用Java語言,如果需要該信息,則使用Netbeans IDE。

+0

是它在Java? – Supersharp

+0

是的。我也在使用NetBeans IDE,以防萬一這會改變任何東西。 –

+1

你正在說明的是不適合switch語句。會鼓勵你使用'if' –

回答

0

您可以轉換爲int,但先乘以不丟失小數點。

double grade = 92.5; 

int convertedGrade = (int) (grade * 10); 

switch(convertedGrade) { 

case 925: System.out.println("Grade is 92.5"); 
    break; 
0

正如其他人指出的那樣,一個switch-case聲明旨在具有離散/枚舉值,這使得它與double數據類型不兼容使用。如果我理解正確的想法,你會希望你的程序很好地轉化考試點到等級,你可以使用一個enum定義的最低點,每個等級:

enum Grade { 

    A(92.5), B(82.5), C(72.5), D(62.5), E(52.5), F(0.0); 

    private static final Grade[] GRADES = values(); 
    private double minPoints; 

    Grade(double minPoints) { 
     this.minPoints = minPoints; 
    } 

    public static Grade forPoints(double points) { 
     for (Grade g : GRADES) { 
      if (points >= g.minPoints) { 
       return g; 
      } 
     } 
     return F; 
    } 
} 

GradeforPoints()方法可以讓你查找與考試點相對應的等級。

現在,爲了跟蹤成績的數量,您可以使用EnumMap<Grade, Integer>而不是個別的計數器變量。請注意,由於查找被編碼到enum,你不再需要switch-case

Map<Grade, Integer> gradeCounters = new EnumMap<>(Grade.class); 

// initialize the counters 
for(Grade g : Grade.values()) { 
    gradeCounters.put(g, 0); 
} 

Scanner input = new Scanner(System.in); 
double total = 0; 
int gradeCounter = 0; 
double points = input.nextDouble(); //read exam points 

while (points >= 0) { 
    total += points; // add points to total 
    ++gradeCounter; // increment number of grades 

    // increment appropriate letter-grade counter 
    Grade g = Grade.forPoints(points); 
    int currentCount = gradeCounters.get(g); 
    gradeCounters.put(g, currentCount + 1); 

    points = input.nextDouble(); 
}