#java#用Scanner獲取鍵盤輸入

題目描述:

成績爲[80, 90)時,等級爲B

成績爲[70, 80)時,等級爲C

成績爲[60, 70)時,等級爲D

成績爲<60時,等級爲E。
(1)使用if-else if語句完成上述任務

(2)使用switch-case語句完成上述任務

代碼:

//首先要引入Scanner這個類;
import java.util.Scanner;
public class SwitchTest
{
	public static void main(String[] args) 
	{
		//從鍵盤輸入;
		Scanner sc=new Scanner(System.in);
		while (sc.hasNextInt()) 
		{
			switch (sc.nextInt()/10) 
			{
				case 10:
				case 9:System.out.println("A");break;
				case 8:System.out.println("B");break;
				case 7:System.out.println("C");break;
				case 6:System.out.println("D");break;
				case 5:
				case 4:
				case 3:
				case 2:
				case 1:System.out.println("E");break;
				default:System.out.println("分數輸入有誤!");
			}
		}
	}
}

用if else實現

//首先要引入Scanner這個類;
import java.util.Scanner;
public class IfElseTest
{
	public static void main(String[] args) 
	{
		//從鍵盤輸入;
		Scanner sc=new Scanner(System.in);
		while (sc.hasNextInt()) 
		{
			/*
			&&運算符規則:a&&b,如果 a 爲true,直接返回 b;如果 a 爲false 那麼直接返回 a。

			|| 運算符規則:a || b,如果 a 爲true,直接返回 a;如果 a 爲false 那麼直接返回 b。
			 */
			if((sc.hasNextInt()<=100)&&(sc.hasNextInt()>=90))
				System.out.println("A");
			else
				if((sc.hasNextInt()<90)&&(sc.hasNextInt()>=80))
					System.out.println("B");
				else
					if((sc.hasNextInt()<80)&&(sc.hasNextInt()>=70))
						System.out.println("C");
					else
						if ((sc.hasNextInt()<70)&&(sc.hasNextInt()>=60))
							System.out.println("D");
						else
							if ((sc.hasNextInt()<60)&&(sc.hasNextInt()>=0))
								System.out.println("E");
							else 
								System.out.println("分數輸入有誤!");
		}
	}
}

會顯示出錯。。。。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章