編輯:只想對迄今爲止幫助過的所有人表示感謝!我是Java新手,我的教授推薦這個網站提供外部幫助。到目前爲止,這是非常棒的。我要花點時間研究代碼並實施我收到的建議。謝謝!不知道要使用哪個迴路
我正在嘗試創建一個程序,將溫度從華氏轉換爲攝氏度,反之亦然。如果用戶沒有輸入正確的單位,程序將循環返回,並要求他們重新輸入單位或輸入Q退出程序。這是我到目前爲止:
我的想法是將一個循環合併到我的switch語句的缺省部分,但我不確定使用哪個循環(可能用於?),它將循環回去並詢問用戶重新進入單位或Q退出。任何幫助真的,真的很感激!我已經堅持了幾個小時!
System.out.print("\tEnter 'F' (or 'f') for Fahrenheit or "
+ "'C' (or 'c') for Celcius: ");
f_or_c = console.next();
double fahrenheit = 5*(temperature-32)/9;
double celcius = (9*(temperature)/5)+32;
switch (f_or_c) {
case "C":
case "c":
System.out.println("\n\t" + temperature + " " + " degrees Celcius "
+ "= " + celcius + " degrees Fahrenheit.");
break;
case "F":
case "f":
System.out.println("\n\t" + temperature + " " + " degrees Fahrenheit "
+ "= " + fahrenheit + " degrees Celcius.");
break;
default:
System.out.println("\n\tUnknown units -"
+ "\n\tCannot do calculation -"
+ "\n\tPlease next time enter either 'F' for Fahrenheit or 'C' Celcius");
System.out.print("\nEnter 'Q' to quit or " +
"any other character to perform another temperature conversion: ");
break;
你實際上正在尋找一種叫做['do-while']的東西(http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html)循環。我試着在我的答案中解釋一下它是如何工作的。 – MirroredFate
嗨。真的很抱歉遲到的回覆。我能夠弄明白,並得到了代碼來執行我的教授想要使用嵌套while循環的方式。我確實看了一下你的do-while循環的例子,因爲它從來沒有傷害知道更多。我將嘗試使用do-while循環方法創建另一個副本。謝謝。 – user3470441