簡體   English   中英

Java 中的 Else-if 語句不起作用,我做錯了什么?

[英]Else-if statement in Java is not working, what am I doing wrong?

所以我試圖用 if-else-if 語句做一個簡單的代碼,但它不起作用。 我之前只做過 if-else 並且我很困惑。 這是代碼。 為什么它不接受我的 else-if?

import java.util.Scanner;

public class DaysOfWeek {
public static void main (String[]args) {
    Double day;
    System.out.print("Enter the day: ");
    Scanner sc = new Scanner(System.in);
    day = sc.nextDouble();
    if (day.equals("Monday"));
    {
        System.out.println("Sounds like someone has a case of the Mondays!");
    }
    else if (day.equals("Wednesday"));
    {
        System.out.println("It's hump day! El ombligo!");
    }
    else if (day.equals("Friday"));
    {
        System.out.println("Finally. It's Friday!");
    }
    else {System.out.println("It's another day of the week.");}
}}
  1. 如果您希望任何比較按書面方式工作,您需要String daysc.nextLine()

  2. if 和 else if 行不應該使用; - 更容易查看您是否喜歡寫

     if (condition) { }

謝謝大家快速指出我的 if-else-if 行末尾的分號。 另外,感謝您抓住字符串而不是雙重,我知道這部分但忽略了它,因為我對 if-else-if 行的混淆感到太沮喪。 一旦我糾正了這兩個問題,它就完全符合我的預期。

String day 和 sc.nextLine() 替換了 Double 以進行適當的比較。

; 已從我的 if-else-if 行的末尾刪除。

我還添加了一點,以便輸入的天數需要各種選項

    import java.util.Scanner;

    public class DaysOfWeek{
    public static void main (String[]args) {
    String day;
    System.out.print("Enter the day: ");
    Scanner sc = new Scanner(System.in);
    day = sc.nextLine();
    if (day.equals("Monday")||day.equals("M")||day.equals("Mon.")||day.equals("Mon"))

    {
        System.out.println("Sounds like someone has a case of the Mondays!");
    }
    else if (day.equals("Wednesday")||day.equals("W")||day.equals("Wed.")||day.equals("Wed"))
    {
        System.out.println("It's hump day! El ombligo!");
    }
    else if (day.equals("Friday")||day.equals("F")||day.equals("Fri.")||day.equals("Fri"))
    {
        System.out.println("Finally. It's Friday!");
    }
    else {System.out.println("It's another day of the week.");}
}}

它與 else-if 無關。 您獲得一個雙輸入( sc.nextDouble() ),然后將其與 String 進行比較。 這永遠不會是真的,因此else將始終被調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM