简体   繁体   中英

Loop input an input X amount of times

i am working on a Mock Test and i am struggling to create a loop that will cycle the input 12 times while adding each input to a sum.

  • Determines the average weight of a person over a particular year.
  • For each month, your algorithm should input the person's weight for that month (a positive real number). Your algorithm should loop, repeating the input, until the input is positive.
  • Finally, your algorithm output the average weight.

After looking through lecture notes on Iteration Control Structures i have come up with this:

public static void main (String [] args)
{
double month, sum;
sum = 0;
for (month = 1; month <= 12; month++)
    {
    month = ConsoleInput.readDouble("Enter weight for each month");
    sum += month;
    }
System.out.println("Sum total is: " +sum);
}

Unfortunately all this does for me is repeat the input an infinite amount of times until i enter a number greater than 12.

I just want to make ConsoleInput cycle 12 times. Does anyone know the best way about this using while, do-while and for loops? I'm not allowed to use arrays, objects etc at this point in the course.

Any advice is appreciated cheers.

您正在以两种方式使用month ,既可以计数到12,也可以接收人的体重。我认为,如果将ConsoleInput.readDouble(..)分配给另一个变量,并将其添加到sum ,程序将可以正常工作更好。

You can Possibly do the Following in order to make your Program Work.Just add one more variable monthweight and assign the user input

public static void main (String [] args)
{
double month, sum,monthweight;
sum = 0;
for (month = 1; month <= 12; month++)
    {

    monthweight = ConsoleInput.readDouble("Enter weight for each month");
    if(monthweight > 0.0M)
      {
        sum += monthweight;
      }
    else
     {
       break;
     }
    }
    System.out.println("Sum total is: " +sum);
}

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