Пока цикл и общие расчеты - PullRequest
0 голосов
/ 11 октября 2018

Я прохожу курс Java в Community College, и у нас есть задание.Задание хочет, чтобы мы попросили пользователя ввести данные о Pythons, вычислить их возраст и сумму их яиц за время их жизни.

Затем он просит нас взять итоговые итоги каждого sumOfEggs и распечатать его для просмотра пользователю.

System.out.println(pythonID + " will lay a total of " + sumOfEggs + " eggs over her remaining lifetime of 20 years.");

У меня есть несколько проблем, связанных с этимЯ ломал головуЯ просмотрел свой учебник, мои предыдущие задания и мои PPT, но я не могу понять это.

Когда я иду на второй цикл, он не запускается заново, он продолжает добавлять 35 к sumOfEggs & previousYearEggs .

Другая проблема заключается в том, что я не могу понять, как сохранить число, представленное в выходных данных

System.out.println(pythonID + " will lay a total of " + sumOfEggs + " eggs over her remaining lifetime of 20 years.");

Ниже приведена вся моя программа:

import java.util.Scanner;
import java.io.*;

public class camelCase
{
   public static void main(String[] args)
   {

      String runProgram = " ";      //declare Run Program
      String pythonID = " ";        //declare Python ID
      int pythonAge = 0;            //declrea the Python's Age
      int previousYearEggs = 0;     //declare Previous Years Eggs
      int currentYearEggs = 0;      //declare current year's eggs
      int sumOfEggs = 0;            //declare sum of eggs
      int years = 0;                //declare years
      int maxAge = 20;              //declare Age Maximum
      int minAge = 1;               //declare Age Minimum
      int overallTotal = 0;

      //create a scanner class for keyboard input
      Scanner keyboard = new Scanner(System.in);

      //Inform the user of this program's purpose
      System.out.println("This is the Python Snake Eggstimator Program.");
      System.out.println("It estimates the number of eggs that a female python will produce over a lifetime.");

      //prompt the user for input
      System.out.println("Please enter HISS if you want to run the program or STOP to quit.");
      runProgram = keyboard.nextLine();
      runProgram = runProgram.toLowerCase();

      //while loop activated when prompted to run program
      while (runProgram.equals("hiss"))
      {

         System.out.println("Please enter the Python ID.");
         pythonID = keyboard.next();

            //initialize the currentYearEggs accumulator
            currentYearEggs = 0;

            //initialize the maxAge accumulator
            maxAge = 20;

            //Prompt user to input the age of the Python
            System.out.println("Enter the Age of the Python in Years.");
            pythonAge = keyboard.nextInt();

            //Invalid Response while loop
            while (pythonAge < minAge || pythonAge > maxAge)
            {
               System.out.println("Invalid Age: Please enter a number between 1 and 20.");
               pythonAge = keyboard.nextInt();
            }

            //Table Header
            System.out.printf("%-5s%20s%20s%20s\n", "Year", "Previous Year Eggs", "Current Year Eggs", "Sum of all Eggs");

            //for loop to calculate the input 
            for (int i = pythonAge; i <= maxAge; i++)
            {
               //initialize currentYearEggs
               currentYearEggs =  35;

               //Calculation for Sum Of All Eggs
               sumOfEggs = sumOfEggs + currentYearEggs;

               //Output data
               System.out.printf("%5d%20d%20d%20d\n", i, previousYearEggs, currentYearEggs, sumOfEggs);

               //calculate the Previous Years eggs
               previousYearEggs = sumOfEggs;


            }//end for


         //output dialogue for user giving details about their input and calculations
         //prompt to restart the program
         System.out.println(pythonID + " will lay a total of " + sumOfEggs + " eggs over her remaining lifetime of 20 years.");
         System.out.println("Enter HISS if you want to run the program or STOP to quit.");
         runProgram = keyboard.next();
         runProgram = runProgram.toLowerCase();

      }//end runProgram while


      System.out.println("The sum of all eggs for all Pythons processed is "); //+ overallTotal);

   }//main

}//class

Заранее благодарен за любую помощь!

1 Ответ

0 голосов
/ 11 октября 2018

Когда я иду на второй цикл, он не запускается заново, он продолжает добавлять 35 к sumOfEggs & previousYearEggs.

Вы инициализируете sumOfEggs в начале вашегоОсновной метод: int sumOfEggs = 0;, но вы не установите его на 0 позже, поэтому он может работать только для первого Python.

Другая проблема заключается в том, что я не могу понять, как сохранить число, представленное в выводе

Вам просто нужно добавить текущий sumOfEggs к вашемуoverallTotal:

//for loop to calculate the input 
sumOfEggs = 0;
for(int i = pythonAge; i <= maxAge; i++) {
    //initialize currentYearEggs
    currentYearEggs = 35;

    //Calculation for Sum Of All Eggs
    sumOfEggs = sumOfEggs + currentYearEggs;

    //Output data
    System.out.printf("%5d%20d%20d%20d\n", i, previousYearEggs, currentYearEggs, sumOfEggs);

    //calculate the Previous Years eggs
    previousYearEggs = sumOfEggs;


}//end for
overallTotal += sumOfEggs;
...