Search code examples
javaloopswhile-loopnested-loops

Nest loop with two while loops


So I have to come up with a code that outputs a report, and I have to enclose this while loop within another while loop, one that will ask the user if he wants to continue inputting info. As long as the user responds "Y", continue asking for required inputs and print the report. Once the user answers "N", then stop further processing.

I just finished the loop that generates the report, but I don't know how to enclose this loop with another loop with the above requirement.

My current code for the report is like this:

while (bookVal > salvageVal){
    //read in stuff

    yearlyDepr = bookVal * (ddRate / 100);
    accDepr = accDepr + yearlyDepr;
    bookVal = bookVal - yearlyDepr;
    year++;

    if (bookVal < salvageVal){
        yearlyDepr = (bookVal + yearlyDepr) - salvageVal;
        accDepr = purchPrice - salvageVal;
        bookVal = salvageVal;

    }
    System.out.printf("%d %,18.0f %,18.0f %,18.0f%n" , year, yearlyDepr, accDepr, bookVal);
}

I tried putting a "read in for Y or N" at the end of this loop and set another while loop on top of it with something like: while (answer == 'Y'), but that just scews up everything...Some help would be nice, thanks!


Solution

  • Scanner s=new Scanner(System.in);
    String toContinue="y";
    while( (your code) && "y".equalsIgnoreCase(toContinue))
    {
          //your code
          System.out.println("Do you want to continue : (Y-to continue,any otherto stop )");
          toContinue=s.next();
    }