Yahoo 知識+ 將於 2021 年 5 月 4 日 (美國東岸時間) 停止服務,而 Yahoo 知識+ 網站現已轉為僅限瀏覽模式。其他 Yahoo 資產或服務,或你的 Yahoo 帳戶將不會有任何變更。你可以在此服務中心網頁進一步了解 Yahoo 知識+ 停止服務的事宜,以及了解如何下載你的資料。

Java程式碼有錯,求解!

import java.util.Scanner;

public class Movie5 {

public static void main(String[] args) {

Scanner a = new Scanner(System.in);

System.out.println("請輸入您的年齡");

int age;

String s;

try{

age =a.nextInt();

if(age<=18){

s ="A";

}else if(age>18&&age<=45){

s ="B";

}else if(age>45&&age<=65){

s ="C";

}else if(age>65){

s ="D";

}

switch(s){

case "A":

System.out.println("您真年輕!前途無量!");

break;

case "B":

System.out.println("您是青壯年,應趁這時好好打拼!");

break;

case "C":

System.out.println("您是中壯年,已成家立業的你,好好做一些自己想做的事!");

break;

case "D":

System.out.println("您真是老當益壯!好好享受老年生活吧!");

break;

}

}

catch(Exception e){

System.out.println("您輸入的非整數!");

}

}

其中switch(s)的地方出現錯誤

該怎麼改?

求高手!

3 個解答

評分
  • NG
    Lv 7
    6 年前
    最愛解答

    import java.util.Scanner;

    public class Movie5 {

    public static void main(String[] args) {

    Scanner a = new Scanner(System.in);

    System.out.println("請輸入您的年齡");

    int age;

    String s = new String(); // 修正: s 沒有初始化

    age =a.nextInt();

    if(age<=18){

    s ="A";

    }else if(age>18&&age<=45){

    s ="B";

    }else if(age>45&&age<=65){

    s ="C";

    }else if(age>65){

    s ="D";

    }

    switch(s){

    case "A":

    System.out.println("您真年輕!前途無量!");

    break;

    case "B":

    System.out.println("您是青壯年,應趁這時好好打拼!");

    break;

    case "C":

    System.out.println("您是中壯年,已成家立業的你,好好做一些自己想做的事!");

    break;

    case "D":

    System.out.println("您真是老當益壯!好好享受老年生活吧!");

    break;

    }

    }

    }

  • 6 年前

    String s;

    變成

    String s = "";

  • ?
    Lv 5
    6 年前

    將字串 s 隨便給個初始值就好了,例如:

    String s = "";

    因為 compiler 認為在使用 s 之前並沒有看到有「明確」給值的地方,所以提出抗議。compiler 並不會去分析程式的邏輯,所以放在條件分支 (if) 裡面的給值動作 compiler 並不認帳 (因為不一定會被執行到)。

還有問題嗎?立即提問即可得到解答。