输入名称,等级,然后打印名称和分类等级

时间:2013-10-22 00:00:08

标签: java switch-statement

我遇到了以下问题:

编写一个Java程序,提示用户输入10名学生的姓名     和他们的成绩作为一个字符串用','分隔。对于每个学生,打印出来     他的名字和分类等级。     **注意:用于循环和切换。     **提示:A(90-100),B(80-89),C(70-79),D(60-69)

     Sample Run:

     Student1: Sara Alhazmi,88
     Output:
     Sara Alhazmi : B

     Student2: Nada Alamri,95
     Output:
    Nada Alamri : A

 (**Repeated 10 times)

以下是我的解决方案:“纠正错误后” 感谢helpe:)

  import java.util.*;
   public class students{
   public static void main(String args[])
  { Scanner input = new Scanner (System.in);
        int f = 10;
        for (int i = 1; i <= f; i++)
    { System.out.println("Student" + i + ":");
     String s = input.nextLine();//s=name student and 
     String name = s.substring(0, s.indexOf(","));//name student 
     String sgrade = s.substring(s.indexOf(",")+1);//grad student
    double grade = Double.parseDouble(sgrade) / 10;// I can not use string with loop so I convert to double because I Divided 
      int ingrade = (int)Math.round(grade); // then I convert to integer 
       switch (ingrade) {
        case 10: 
         System.out.println(name + ": A");
        break;
         case 9:
        System.out.println(name + ": A");
            break;
         case 8: 
       System.out.println(name + ": B"); 
         break;
         case 7: 
     System.out.println(name + ": C");
        break;
         case 6:
       System.out.println(name + ": D");
          break; 

   }//end  while loop
  }//end for loop
 }// end main
 }// end class

1 个答案:

答案 0 :(得分:1)

就像@KeepCalmAndCarryOn所说,你的switch语句需要包含范围,而不仅仅是个别数字。可以根据if / else if来考虑它,这将有助于您重新定义您的开关。