我正在寫一個主要方法,要求用戶以圓錐體的半徑和高度的長度的形式輸入,然後調用3個其他數學方法來確定圓錐體底部的面積作爲它的表面積和體積。爲什麼這個循環不支持前兩個輸入?
這個想法是,你應該能夠輸入多組輸入,並通過輸入「q」表示你已完成輸入。示例輸入可以例如是「10 5 6 8 7 5 q」。然後程序應該計算三次,用兩組半徑和高度計算,然後打破循環。相反,它忽略了前兩個輸入,並且完美地完成了其餘四個輸入。它基本上計算n-1組高度和半徑,其中n是提供的組數。我非常感謝這方面的幫助。
while(true) //Infinite loop
{
if (scan.hasNextInt()) //If next input is an integer, read it
{
radie = scan.nextInt();
height = scan.nextInt();
}
else if (scan.next().equals('q'))
{ //If it instead if "q", break the loop
break;
}
do
{
if (scan.hasNextInt())
{
radie = scan.nextInt();
height = scan.nextInt();
}
System.out.print("r = "+radius);
System.out.println("h = "+height);
System.out.println("Bottom area: "+ area(radius));
System.out.println("Surface area: "+area(radie, height));
System.out.println("Volume: "+ volume(radius, height));
}while (scan.next() != "\n");
}
謝謝,這解決了問題!我不知道我怎麼沒有看到。我在下面發佈了更新的代碼,因爲我現在又遇到了另一個問題。當我輸入例如「10 5 3 4 q」時,程序應計算兩組輸入,然後繼續。但是,它現在計算三組,最後兩組相同。任何猜測爲什麼這可能是? –
因爲你的else if(scan.next()。equals('q'))break;'語句檢查'char''q',但掃描器讀取它作爲一個整體'string',因爲你正在調用'scan .next()'輸入令牌,因此不會中斷while循環。用雙引號括住你的'q'。檢查我的答案的第一個代碼片段。 –
此外,請將您的編輯發佈在原始問題本身的下方,而不是將其作爲答案提交。考慮在問題中移動它並刪除您的答案。 –