iT邦幫忙

2025 iThome 鐵人賽

DAY 2
0

目的

日期格式錯誤時不讓程式崩潰。
使用者輸入非數字提醒重新輸入。
輸入不合理值給出提示
在輸錯時會重新回到輸userId那裡,不會回到主選單。
把每個功能都新增是否繼續的選擇。

1.主選單
這裡原本有sc.nextLine,刪掉是因為後面的try已經要讀使用者輸入的值了,如果沒刪掉的話,會把使用者輸入的值跳過,需再按一次Enter。
(nextLine通常用在前面是nextInt/nextDouble後面是nextLine的中間)
String input = sc.nextLine().trim():讀取使用者輸入的值,並去掉前後空白或換行符號,結果存入變數input。
if(input.isEmpty()):檢查使用者是不是直接按Enter,是的話印出提醒字串。
continue:回到迴圈,重新顯示選單。
choice = Integer.parseInt(input):把剛讀進來的值轉字串並存入變數choice。
catch(NumberFormatException e):捕捉上面try可能發生的例外,像是輸入不是整數。
https://ithelp.ithome.com.tw/upload/images/20251013/20178845WrLdYgbc4q.jpg


2.case 1
這裡放while(true)是因為如果輸入錯的話,不會回到主選單,會回到輸入userId那裡。
(如果想要回到輸入當下那裡,要在每個欄位寫while,這裡沒寫)
try-catch:檢查有沒有輸入格式錯誤
String userStr = sc.nextLine().trim():讀取使用者輸入的值,並去掉前後空白或換行符號,結果存入變數userStr。
if:如果輸入值為空,印出提示字串,並返回輸入userId,否則把字串轉成int並存入變數userId。
後面foodId、份量同樣道理。
double quantity=Double.parseDouble(qtyStr):把字串轉成浮點數,存進變數quantity。
數字輸錯格式會丟出NumberFormatException例外。
https://ithelp.ithome.com.tw/upload/images/20251013/20178845rErtGo44cD.jpg
LocalDate.parse(date):把字串轉成LocalDate物件。
日期輸錯格式會丟出DateTimeParseException例外。
https://ithelp.ithome.com.tw/upload/images/20251013/201788452luOkaZj5u.jpg


case 2
前面和1一樣的寫法。
https://ithelp.ithome.com.tw/upload/images/20251013/20178845A70BQPKJoD.jpg
這裡我希望可以一次查詢多筆資料,所以加了新增功能。
https://ithelp.ithome.com.tw/upload/images/20251013/20178845leYeZsJn8j.jpg


case 3
跟上面的一樣。
https://ithelp.ithome.com.tw/upload/images/20251013/201788450WxPlHYAww.jpg
https://ithelp.ithome.com.tw/upload/images/20251013/20178845KouZfcP2GH.jpg


case 4
跟上面一樣。
https://ithelp.ithome.com.tw/upload/images/20251013/20178845LMH8E6IH29.jpg
https://ithelp.ithome.com.tw/upload/images/20251013/20178845kjFtFiSjzH.jpg


執行結果
https://ithelp.ithome.com.tw/upload/images/20251013/20178845IdMzhxTlSn.jpg
https://ithelp.ithome.com.tw/upload/images/20251013/20178845sINwoj68B2.jpg
![https://ithelp.ithome.com.tw/upload/images/20251013/20178845jnHoMuqVA0.jpg](https://ithelp.ithome.com.tw/upload/images/2
0251013/20178845jnHoMuqVA0.jpg)
https://ithelp.ithome.com.tw/upload/images/20251013/20178845XnQtigAO7j.jpg
https://ithelp.ithome.com.tw/upload/images/20251013/20178845LbW6E0zIhh.jpg
https://ithelp.ithome.com.tw/upload/images/20251013/20178845fJosbYueNW.jpg


上一篇
優化輸入介面
下一篇
寫計算單日總熱量的方法
系列文
飲食營養追蹤 + 健康分析 Web 系統16
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言