360Kpop LogoGame cho Sky

bài tập java #7 : Switch

Bài 8 – switch
Bạn đã học xong if. Bạn muốn dùng vòng lặp if để đánh giá điểm số nhập vào. Bạn sẽ viết chương trình sau đây

PHP Code:
import java.io.*;
public class 
Hello {
                public static 
void main(String[] argsthrows Exception {
                                
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                                
System.out.print("Nhap diem so: ");
                                
int diem Integer.parseInt(in.readLine());
                                if(
diem<=2System.out.println("Yeu");
                                if((
diem>2) && (diem<=3)) System.out.println("Trung binh");
                                if((
diem>3) && (diem<=4)) System.out.println("Kha");
                                if((
diem>4) && (diem<5)) System.out.println("Gioi");
                                if(
diem==5System.out.println("Xuat sac");
                }
}  


Thay vì lặp lại những câu if ấy, bạn nên dùng switch

PHP Code:
import java.io.*;
public class 
Hello {
                public static 
void main(String[] argsthrows Exception {
                                
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                                
System.out.print("Nhap diem so: ");
                                
int diem Integer.parseInt(in.readLine());
                                switch(
diem)
                                {
                                                case 
0:
                                                case 
1:
                                                case 
2:System.out.println("Yeu");break;
                                                case 
3:System.out.println("Trung binh");break;
                                                case 
4:
                                                case 
5:System.out.println("Gioi");break;
                                                default:
System.out.println("Vao sai");
                                }
                }
}  


*break với switch: break sẽ thoát ngay ra khỏi khối lệnh trong thân của switch 



Viết bình luận mới

Mua lịch Kpop 2013: Đồng hành cùng thần tượng trong năm mới!