2016-04-14 137 views
0

我正在爲我的班級做一個年級平均腳本,我無法計算如何讓我的交叉檢查部分重複,直到我有一個有效值(代碼如下所示)。運行時,如果原始輸入無效,但只能執行一次,則允許我進行更正。我如何才能循環,直到我得到正確的迴應?提前致謝!創建複查if語句

if (grade1 >= 0 && grade1 <= 100) 
    System.out.println("First grade valid.\n"); 
    else 
    { 
     System.out.println("Grade invalid. Re-enter first grade:"); 
     grade1 = kb.nextDouble(); 
    } 

回答

1

考慮

grade = -1; 
System.out.println("Enter a grade:\n"); 
grade1 = kb.nextDouble(); 
if (grade1 >= 0 && grade1 <= 100) 
{ 
    System.out.println("First grade valid.\n"); 
} 
else 
{ 
    while (grade1 < 0 || grade1 > 100) 
    { 
     System.out.println("Grade invalid. Re-enter first grade:"); 
     grade1 = kb.nextDouble(); 
    } 
} 
+0

只是去嘗試編輯和它否定重新進入的能力。 – Dayeo78

+0

你應該在循環中有重入代碼。請張貼循環顯示您如何用FredK的建議重構它。只是發佈「它不起作用」不能爲任何人提供足夠的信息來幫助你。 –

+0

完美,這就是我一直在尋找的!謝謝您的幫助! – Dayeo78

0

試試這個:

while ((grade = Integer.parseInt(JOptionPane.showInputDialog("Enter a grade"))) < 0 || grade > 100) { 
    System.out.println("Invalid grade of: " + grade); 
} 

它不處理信件很好不過,如果你輸入 「A」 ITLL抱怨,你

0

甜心吆喝,作爲最初執行的方法,我進行了設置,以便用戶在輸入後插入輸入並交叉檢查其有效性ered(見下面的第一段摘錄)。如果我能夠主動交叉檢查初始輸入(見下面第二段摘錄),最好節省空間。盧布洛克,我明白你在做什麼,這是我的一個小小的疏忽。從現在起,我的反應會更好。

//交叉檢查

if (grade1 >= 0 && grade1 <= 100) 
    System.out.println("First grade valid.\n"); 
    else 
    { 
     System.out.println("Grade invalid. Re-enter first grade:"); 
     grade1 = kb.nextDouble(); 
    } 

//入門級

grade1 = kb.nextDouble(); 
    while (grade1 < 0 || grade1 > 100) 
    { 
    System.out.println("Entered grade is invalid. Re-enter grade:"); 
    grade1 = kb.nextDouble(); 
    } 
0
try (Scanner scanner = new Scanner(System.in)) { 
    System.out.println("Enter a grade:\n"); 
    double grade1 = scanner.nextDouble(); 
    if (grade1 >= 0 && grade1 <= 100) 
    { 
     System.out.println("First grade valid.\n"); 
    } 
    else 
    { 
     while (grade1 < 0 || grade1 > 100) 
     { 
      System.out.println("Grade invalid. Re-enter first grade:"); 
      grade1 = scanner.nextDouble(); 
     } 
    } 
}