1. 程式人生 > >完成成績等級輸出程式

完成成績等級輸出程式

步驟一:

定義一個類及main方法

public class LevelForIf {

public static void main (String 【】args){

步驟二:

讀取控制檯的輸入

在main方法中,例項化Scanner類,並呼叫Scanner類的nextInt方法接收使用者所錄入的學員分數,使用完畢後將scanner物件關閉。程式碼如下所示

ipmort java.util.Scanner;

public class LevelForIf{

public static void main(String 【】args){

Scanner  scanner = new Scanner(System.in);

System.out.println("請輸入學員的分數(0-100):");

int score = scanner.nextInt();

步驟三:

使用if-else語句進行判斷

先使用if語句判斷所錄入的分數是否在0到100之間;如果不在正確的範圍,則先輸出提示資訊,再使用 return 終止方法的執行。

如果錄入的分數確實在 0-100 之間,則使用 if-else 結構判斷不同的分數段並輸出不同的級別。程式碼如下所示:

ipmort java.util.Scanner;

public class LevelForIf{

public static void main(String 【】args){

Scanner  scanner = new Scanner(System.in);

System.out.println("請輸入學員的分數(0-100):");

int score = scanner.nextInt();

scanner.close();

if(score>100||score<0){

System.out.println("輸入分數錯誤");

}else if(score>=90){

System.out.println("A");

}else if(score>=80){

System.out.println("B");

}else if(score>=60){

System.out.println("c");

}else{

System.out.println("D");

}