我的代碼有問題,我無法離開循環。我必須創建一個程序,我輸入一個數字,然後我被要求輸入大於第一個值的奇數值。例如,我輸入12,爲了結束程序,我必須輸入13,15,17或任何大於12的奇數。如果我輸入一個數字,即使它告訴我再試一次。如果我輸入一個奇數(3)低於值(12),它告訴我,我必須輸入一個大於12的值。不能出去做while循環
我知道這個程序的邏輯如何工作,以及我認爲我在做什麼對的。 好吧,當我運行程序和輸入12例如,然後輸入下一個值(15),它做它應該做的。但我輸入12,然後輸入一個數字低於12像3或或偶數,而不是一個奇數值大於12,它不斷告訴我再試一次,即使我輸入一個很好的值,如15。基本上循環不斷重複它自我一遍又一遍。
我是新來的java所以它很難找出我做錯了什麼。我已經研究while循環,但我無法弄清楚如何擺脫循環。
這是我的代碼到目前爲止。
import java.util.*;
public class bonus2 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Please Enter any number: ");
int theValue = getBigOddValue(0);
System.out.printf("The Value gotten was %d. \n", theValue);
}
private static int getBigOddValue(int value) {
value = input.nextInt();
System.out.printf("Enter an odd number greater than " + value + ": ");
int cutoff = input.nextInt();
int val = cutoff;
while (val % 2 == 0){
System.out.printf("The number is even. Try again: ");
input.nextInt();
}
while (val<value){
System.out.printf("The number must be greater than " + value
+ ". Try again: ");
input.nextInt();
}
return cutoff;
}
SAMPLE RUNS(我的跑步應該如何)。
**Call (and return displayed):**
theValue =getBigOddValue(14);
System.out.printf("The value gottenwas %d.\n",theValue);
**Machine-user interaction of above:**
Enter an odd number greater than 14: 2
The number is even. Try again: 28
The number is even. Try again: 11
The number must be greater than 14. Try again: 3
The number must be greater than 14. Try again: 18
The number is even. Try again: 9
The number must be greater than 14. Try again: 19
The value gotten was 19.
如果您已經刪除了您的代碼,您也是這個問題無效的。如果安全對你很重要,保持一個乾淨而有意義的網站對於SO參與者來說是重要的。刪除你的問題。 – Siddharth 2013-05-07 04:42:36
我不能,因爲它說它已經有答案了。 – Guille 2013-05-07 23:32:58
寫入meta.stackoverflow.com。他們可以幫助。 – Siddharth 2013-05-08 04:10:21