[問題] if-else 新手發問

看板java作者 (胖胖)時間18年前 (2007/09/30 21:42), 編輯推噓7(701)
留言8則, 5人參與, 最新討論串1/1
import java.io.*; public class test { public static void main(String args[]) throws IOException { BufferedReader buf; String str; int act; double weight,tcalorie,ncalorie; buf=new BufferedReader(new InputStreamReader(System.in)); System.out.println("請輸入體重(公斤)"); str=buf.readLine(); weight=Double.parseDouble(str); System.out.println("請輸入今天所吃進的熱量"); str=buf.readLine(); tcalorie=Double.parseDouble(str); System.out.println("活動量大請輸入1,普通請輸入2,低請輸入3"); str=buf.readLine(); act=Integer.parseInt(str); ----------------------------------------------- if(act==1) ncalorie=weight*22/0.6; else if(act==2) ncalorie=weight*22/0.65; else ncalorie=weight*22/0.75; ----------------------------------------------- str=(tcalorie>ncalorie)?("吃太多了")"請繼續保持"); System.out.println(str); } } 上面情況可以順利編譯 請問為什麼如果在有虛線包圍的這段程式碼我使用 if(act==1) ncalorie=weight*22/0.6; if(act==2) ncalorie=weight*22/0.65; if(act==3) ncalorie=weight*22/0.75; 會顯示variable ncalorie might not have been initialized呢??? 是不能這樣用嗎? -- ※ 發信站: 批踢踢實業坊(ptt. cc) ◆ From: 122.126.24.8

09/30 21:52, , 1F
紅色在哪.... 順便先看一下你的變數在哪
09/30 21:52, 1F

09/30 21:53, , 2F
JAVA比較嚴謹 因為你初始化的ncalorie是空值
09/30 21:53, 2F
※ 編輯: a613204 來自: 122.126.24.8 (09/30 22:23) ※ 編輯: a613204 來自: 122.126.24.8 (09/30 22:23) ※ 編輯: a613204 來自: 122.126.24.8 (09/30 22:25) ※ 編輯: a613204 來自: 122.126.24.8 (09/30 22:28)

09/30 22:28, , 3F
那為什麼使用else就可以順利編譯呢..?
09/30 22:28, 3F

09/30 22:33, , 4F
只有if可能有通通不成立的情況 有else則至少會成立
09/30 22:33, 4F

09/30 23:01, , 5F
因為加了else會滿足 lazy 初始的條件, 就不會沒有初始值
09/30 23:01, 5F

10/01 01:01, , 6F
樓上專業XD
10/01 01:01, 6F

10/01 01:01, , 7F
原PO的問題 我從學CPP改學JAVA的時候也一直碰到(  ̄ c ̄)y
10/01 01:01, 7F

10/01 11:59, , 8F
感謝各位 問題已解決
10/01 11:59, 8F
文章代碼(AID): #16_wUpD0 (java)
文章代碼(AID): #16_wUpD0 (java)