2014-10-10 24 views
0

我的程序是假設提示用戶輸入與多少次考試相關的考試分數。這很好,但是,當用戶輸入負面考試分數時,應該讓他們再次重新參加所有三項考試。我的課程保存了所有不是負面的考試,因此當您重新進入三門考試時,它只使用完成三門考試所需的人數。可能有些東西很容易丟失,因爲我是新手。我認爲下面的代碼對於答案是足夠的,但是如果它是一個更大的問題,那麼我就有更多的代碼,然後我期待着。我無法理解如何重置此循環/掃描儀

System.out.print("Enter exam scores  :"); 

for(int y = 1; y <= numberofexams; y++) { 
    examgrades = NumScanner.nextDouble(); 

    while(examgrades < 0) { 
     NumScanner.nextLine(); 
     System.out.print("Invalid exam scores, reenter scores: "); 
     examgrades = NumScanner.nextDouble(); 
    } 

    System.out.println(); 

    if(y > numberofexams) break; 

    sum += examgrades; //exam average 
    sum2 += examgrades; //class average 


} // number of exams 

回答

1

我不明白爲什麼你需要的while循環,你爲什麼掃描nextLine()? 試試這個代碼:

System.out.print("Enter exam scores  :"); 

for(int y = 1; y <= numberofexams; y++) { 
    examgrades = NumScanner.nextDouble(); 

    if(examgrades < 0) { 
    y = 1; 
    continue; 
    } 

    System.out.println(); 

    if(y > numberofexams) break; 

    sum += examgrades; //exam average 
    sum2 += examgrades; //class average 


} // number of exams 
+0

是的,這是我所需要的,現在它完美的工作。我非常確定這是一件小事。非常感謝。 – Krysiak 2014-10-10 17:18:27