2014-02-22 4 views
0

두 가지 질문. 3 개 이상의 'if'문을 사용할 때 switch 문을 사용하는 것이 가장 좋습니다. 그럴까요? 둘째 Java : 다중 표현식에 switch 문 사용?

는, 누군가가 다음 코드를 검토하고 변수 '등급은'항상
while (!"Y".equalsIgnoreCase(exit)) 
     { 
       i++; 
       System.out.print("Please enter name of assignment " + i + ": "); 
       assignment = user.nextLine().toUpperCase(); //consumes string + \n 
       System.out.print("Please enter points earned: "); 
       earned = user.nextDouble();//consumes double 
       user.nextLine();//consumes \n 
       System.out.print("Please enter total points possible: "); 
       total = user.nextDouble(); 
       user.nextLine(); 



     System.out.print("Assignment\t"); System.out.print("Score\t"); System.out.print("Total Points\t"); System.out.print("Percentage\t\n"); 


     System.out.print(assignment + "\t\t"); System.out.print(earned + "\t"); System.out.print(total + "\t\t"); System.out.print(percent.format(earned/total) + "\n\t"); 


     // Putting user data into an array for calculation: 
      double[] calc; calc = new double[4]; 
       calc[i] = earned; // Array elements coincide with the current iteration loop 

      double[] totalPoints; totalPoints = new double[4]; 
       totalPoints[i] = total; 


     for (double e : calc) // adds up all the stored data in the array 
      sum += e; 


     for (double f : totalPoints) // adds up all the stored data in the array 
      tot += f; 




    char grade = '0'; 
      if (sum/tot >= 90) 
      { 
       grade = 'A'; 
      } 

      else if (sum/tot >= 80 && sum/tot <= 89.99) 
      { 
       grade = 'B'; 
      } 

      else if (sum/tot >= 70 && sum/tot <= 79.99) 
      { 
       grade = 'C'; 

      } 

      else if (sum/tot >= 60 && sum/tot <= 69.99) 
      { 
       grade = 'D'; 

      } 

      else if (sum/tot <= 59.99) 
      { 
       grade = 'F'; 

      } 
     System.out.println("Your total is " + sum + " out of " + tot + ", or " + percent.format(sum/tot) + ", and your grade is an " + grade); 

     } 
F.

결과 이유 다 표현되고 또는 B가 설명이기는하지만 switch 문으로 변환하는 방법 A에 나에게 아이디어를 줄 수
+1

변수에 보유하고있는 소리가 들리면 모든 임계 값을 '100'으로 나누어야합니다. – Keppil

+0

'sum'및 'tot'의 값을 모른 채 어떻게 의견을 말 할 수 있습니까? –

+0

'switch'는 범위가 아닌 구체적인 값으로 작업 중입니다. – nikis

답변

0

@Keppil가 언급 한 바와 같이, sum/tot 아마 항상 0과 1 사이의 값 을 얻을 수 있습니다. 그것을 비교하는 기준을 변경하고 싶을 수도 있습니다 (예 : 90 대신 0.9 등). 당신이 경우 (합/TOT> = 90) 조건을 만족하지 않은 반면에

는, 당신은 sum/tot엄격 미만 90 것을 확실히 알고있다. 따라서 sum/tot <= 89.99 일 경우 다음 테스트를 체크 인 할 필요가 없습니다. 그건 그렇고 위험 할 수 있습니다. sum/tot == 89.999? 귀하의 조건 중 어느 것도 만족할 수 없습니다.

나는이 같은 등급 산출 방법을 만드는 것이 좋습니다 :

public static char gradeFor(final float tot, final float sum) { 
    float ratio = tot/sum; 

    if(ratio >= 0.9f) { 
     return 'A'; 
    } 

    if(ratio >= 0.8f) { 
     return 'B'; 
    } 

    if(ratio >= 0.7f) { 
     return 'C'; 
    } 

    if(ratio >= 0.6f) { 
     return 'D'; 
    } 

    if(ratio >= 0.5f) { 
     return 'E'; 
    } 

    return 'F'; 
} 
가 가 마지막으로 한가지

: 당신이 E를 반환 할 수있는 어떤 경우가없는 것 같다 ... 그것입니다 예정된? (

  • totsum
  • 이 임계 값은 당신이에 대해 테스트하는 값과 일치하는지 확인 진수 값이 있는지 확인을 :

    난 당신이 조사 싶어 할 수 있다고 생각, 요약하면 @ 케필이 언급 한대로 대부분 100f으로 나눠야 할 것입니다.)
  • 코너 대소 문자가 누락되지 않았는지 확인하십시오 (예 : tot/sum이 89보다 큰 경우).

건배 P) : 99낮은

  • 당신이 구현 된 행동이 당신이 할 의도 있는지 확인) (90)보다 (당신이 'E'를 반환 할 수 없다는 사실은 좀 나를 귀찮게!

  • 0

    나는 스위치 경우가이 경우에 매우 잘 작동 생각하지 않지만, keppil 위에서 말했듯이, 당신은

    private float total = sum/tot * 100;

    즉 다른 임계 값을 float와 경우 문을 평가해야 5,149,

    때문에 지금은 문이 적합 다음 경우 검사해야 할 값의 범위가있을 때 합/TOT는 소수

    0

    로 평가 아픈 내기를 의미한다.
    특정 값을 확인할 때 switch 문이 적합합니다.

    코드에서 if 문은 괜찮습니다. 당신은 다음과 같은 것을 작성하여이를 개선 할 수 있지만 :

    public class Grade 
    { 
        public Grade() 
        { 
        float score = 95; 
        float total = 100; 
    
        char grade = getGrade(score); 
    
        System.out.println("Score: " + score); 
        System.out.println("Total: " + total); 
        System.out.println("Grade: " + grade); 
        } 
    
        private char getGrade(float score) 
        { 
        char grade = 'F'; 
    
        if (score >= 90) 
         grade = 'A'; 
    
        else if (score >= 80) 
         grade = 'B'; 
    
        else if (score >= 70) 
         grade = 'C'; 
    
        else if (score >= 60) 
         grade = 'D'; 
    
        return grade; 
        } 
    
        public static void main(String[] args) 
        { 
        new Grade(); 
        } 
    } 
    
    0

    switch 문을 사용하는 것이 항상 좋은 것은 아닙니다. 왜? switch 문은 기본 데이터 형식과 열거 형에서만 작동합니다. 그러나 바이트, 두배, 정수 등의 기본 유형에 래퍼 클래스를 사용할 수 있습니다.