简体   繁体   中英

I can't understand how to reset this loop/scanner

My program is suppose to prompt user to enter exam scores related to how many exams that were taken. That works fine however, when a user enters a negative exam score it is supposed to make them reenter all three exams again. My program saves any exam that was not negative so when you reenter the three exams it only uses how many it needs to complete the three or how many it is looking for. There is probably something really easy that I'm missing because I'm new to this. I think the code below is enough for an answer however, I have a lot more code if it is a bigger problem then I'm expecting.

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

i dont see why you need the while loop, and why do you scan nextLine() ? try this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM