2016-07-26 324 views
-4

最近,我一直在練習上的Java我的新手教程, 但是我被困與if else語句,如果else語句

我的主要重點是讓用戶如果用戶嘗試大於5次寫,它將返回false,否則它將返回true。

任何幫助將不勝感激。

int userTry = 0; 
double value1 = 0; 
Scanner useranswer1 =new Scanner(System.in); 

if(userTry == 5){ 
    do{ 
     System.out.println("What is 10 divided by 4?"); 
     value1 = useranswer1.nextDouble(); 

    } 
    while(value1 != 2.5); 
    System.out.println("You got the right answer"); 
    } else { 

    } System.out.println("You have zero more tries"); 
} 
+1

你必須把你的循環周圍如果不是相反 –

+0

做一個循環,它允許人去嘗試最多五次。一個'for''循環似乎對此很好。如果得到正確的答案(使用'if'來檢查這個)'break'循環。 – ifly6

+1

改變你while while循環包括嘗試次數 –

回答

1

試試這個:

do{ 
    System.out.println("What is 10 divided by 4?"); 
    value1 = useranswer1.nextDouble(); 
    userTry++; 
} 
while(value1 != 2.5 && userTry != 5); 
if(userTry == 5){ 
     System.out.println("You have zero more tries");  
} else { 
    System.out.println("You got the right answer"); 
} 
+2

Jérèm錯誤,因爲在用戶嘗試== 4時,你會增加到5,但他實際上得到了正確的答案。但是你會打印出「你沒有更多的嘗試」。 – Deceiver

+0

當然,這只是一個提示... –

+0

夠公平的。 ;) – Deceiver

2

關鍵是要設置您do-while循環的基礎上,檢查該用戶沒有得到正確的值,如果他們有足夠的重試條件。

如果用戶獲得了正確的值,他們已經完成了所需的重試次數,否則嘗試次數爲零。希望這可以幫助。

int userTry = 0; 
double value1 = 0.0; 
Scanner useranswer1 = new Scanner(System.in); 

do { 
    System.out.println("What is 10 divided by 4?"); 
    value1 = useranswer1.nextDouble(); 
} while (value != 2.5 && ++userTry < 5); // NOTE: pre-increment and check. If you like to have a safer version, move this increment inside the while loop. 

if (value1 != 2.5) { 
    System.out.println("You have zero more tries"); 
} else { 
    System.out.println("You got the right answer!"); 
} 
3

嘗試以下操作:

int userTry = 0; 

    double value1 = 0; 
    Scanner useranswer1 =new Scanner(System.in); 

    for (int userTry = 5; userTry > 0; userTry--) 
     System.out.println("What is 10 divided by 4?"); 
     value1 = useranswer1.nextDouble(); 
     if (value1 == 2.5) break; 
     System.out.println(); // empty line 
    } 

    if (value1 == 2.5) { 
     System.out.println("You got the right answer"); 
    } else { 
     System.out.println("You have zero more tries"); 
    } 
} 
+0

這個答案比沒有理由做一個'do-while'循環更有意義 – ifly6

+0

難道是while while循環是當天的話題,循環還沒有被討論過嗎?這看起來像是一個學習者的情況。 –

2
int count = 0; 
    double trueAnwer = 6.66; 
    while (true) { 
     count++; 
     Scanner useranswer1 =new Scanner(System.in); 
     if (trueAnwer == useranswer1.nextDouble()) { 
      System.out.println("You got the right answer"); 
      return; 
     } 
     if (count==5) { 
      System.out.println("You have zero more tries"); 
      return; 
     } 
     System.out.println("This is "+count+" times"); 
    } 
+0

你不想爲循環的每次迭代實例化你的'useranswer1' - 否則好。 –