[英]Java do while not looping
我確定這將是愚蠢的,但是我不能讓while循環工作,有人可以看一下嗎? 我需要用戶輸入一個數字,然后在while循環中對此進行驗證。 然后,此數字將添加到arraylist中,並一直循環播放,直到用戶輸入“ -1”為止。 這是我的代碼:
public void enterValues(Scanner scan, ArrayList<Double> values) {
do {
System.out.print("Enter value to convert: £");
while (!scan.hasNextDouble()) {
System.out.println("Please enter a double");
scan.nextLine();
}
values.add(scan.nextDouble());
System.out.print("Value entered. Enter -1 to stop: ");
}
while (!scan.next().equals("-1"));
System.out.println("Values entered. Returning to main menu.");
mainMenu(scan, values);
這將為您工作。
public void enterValues(Scanner scan, ArrayList<Double> values){
Double dValue= (double) 0;
do{
System.out.println("Enter value to convert: £");
dValue= scan.nextDouble();
if(dValue != -1)
values.add(dValue);
}while(dValue != -1);
System.out.println("Values entered. Returning to main menu.");
mainMenu(scan, values);
}
這與下面的其他答案類似,但更為慣用。 無需檢查輸入值兩次。 只需檢查一次即可,如果結果為負,請使用break
退出循環。
public void enterValues(Scanner scan, ArrayList<Double> values) {
for( ;; ) {
System.out.print("Enter value to convert: £");
while (!scan.hasNextDouble()) {
System.out.println("Please enter a double");
scan.nextLine();
}
double input = scan.nextDouble();
if( input < 0 ) break;
values.add( input );
System.out.println("Value entered. Enter -1 to stop: "+ values );
}
}
如果您實際上需要“ -1”,而不僅僅是負數,請注意,將double與==
進行比較是不明智的做法。 使用公差與差異。 還要注意下面的內容,我在程序中提供輸入以創建SSCCE 。
public class ScannerTest
{
private static final String[] testVectors = {
"123\n456\n890\n-1\n",
};
public static void main(String[] args) {
for (int i = 0; i < testVectors.length; i++) {
String testInput = testVectors[i];
Scanner scan = new Scanner(testInput);
ArrayList<Double> output = new ArrayList<>();
new ScannerTest().enterValues( scan, output );
System.out.println( output );
}
}
public void enterValues(Scanner scan, ArrayList<Double> values) {
for( ;; ) {
System.out.print("Enter value to convert: £");
while (!scan.hasNextDouble()) {
System.out.println("Please enter a double");
scan.nextLine();
}
double input = scan.nextDouble();
if( compareDouble( input, -1.0, 0.00001 ) ) break;
values.add( input );
System.out.println("Value entered. Enter -1 to stop: "+ values );
}
}
private boolean compareDouble( double d1, double d2, double tolerance ) {
return Math.abs( d1 - d2 ) < tolerance;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.