Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: How do I loop with an If statement

  1. #1
    Junior Member
    Join Date
    Sep 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default How do I loop with an If statement

    Here is what the program needs to be able to do:

    //Run1

    "Enter loan amount: 100000
    Enter rate: 6
    Enter number years: 30

    The monthly payment is: $599.55

    Would you like to calculate again (y/n): y"

    // Run 2

    Enter loan amount: -110000
    Enter rate: 5
    Enter number years: 6

    You must enter positive numeric data!

    Would you like to calculate again (y/n): n


    - If the user inputs a negative number the program tells you to enter positive numeric data.
    - If the user inputs "y" then the program goes back to the beginning if they enter "n" then the program exits.
    - I have to use the in.nextLine() method , and the String.equals(string2) method .

    I do not quite understand the loop statements. I have tried a while loop and do loop. The if statement inside the loop and outside the loop. I'm lost on this. Can someone point me in the right direction.

    How do I write the loop?

    package assignment2b;
     
    import java.util.Scanner;
     
     
    public class Assignment2b {
     
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
     
        Scanner in = new Scanner(System.in); // input object
     
        double loanAmount;                                      // user input
        double interestRate;                                    // user input
        double yearNumber;                                      // user input
        double monthlyPayment;                                  // payment from math.pow
        double finalPayment;                                    // actual payment displayed
        double monthNumber;                                     // number of months
        double monthlyRate;                                     // interest rate by month
     
     
        System.out.print("Enter loan amount: ");                // Line to input loan amount
        loanAmount = Double.parseDouble (in.nextLine());        // Gets input number
     
     
        System.out.print("Enter rate: ");                       // Line to input rate amount
        interestRate = Double.parseDouble (in.nextLine());      // Gets input number
     
        monthlyRate  = interestRate /100 /12;                   //Convert rate into decimals
     
     
        System.out.print("Enter number years: ");               // Line to input number of years
        yearNumber = Double.parseDouble (in.nextLine());        // Gets input number
     
        monthNumber = yearNumber * 12;                          // Total amount of months  
     
        monthlyPayment = Math.pow(1+monthlyRate , monthNumber) / (Math.pow(1+monthlyRate, monthNumber)-1);
     
        finalPayment = (loanAmount*monthlyRate*monthlyPayment); // Gives the payment          
     
     
     
     
        if (loanAmount <= 0 || interestRate <=0 || yearNumber <=0)                                                  // incorrect# line
         {       
          System.out.println("\nYou must enter positive numeric data!");
          System.out.println("\nWould you like to calculate again (y/n): ");
          in.nextLine();
        }
     
        else                                                                   // correct# line
        {    
        System.out.printf("\nThe monthly payment is: $%.2f", finalPayment);   // Monthly payment
        System.out.println(); 
        System.out.println("\nWould you like to calculate again (y/n): ");
        in.nextLine();
        System.out.println();                                                 // Moves build line
        } 
     
     
     
     
     
     
     
        }    
    }
    Last edited by DaveK; October 2nd, 2014 at 09:37 AM.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: How do I loop with an If statement

    The answer to the question posed by your thread title is, You don't. if() and if()/else statements are branching tools that logically determine which path the program will take from a number of possible paths but cannot return execution to the beginning of the if() logic. Loops are for(), while(), and do/while() statements.

    What you a trying to do is input validation. If the user provides a number of inputs, validation should be done immediately after each input has been obtained, not after all inputs have been obtained. If you were using multiple methods, I would suggest that a method be used to obtain and validate each input. I suspect you're not using methods beyond the main() method, so then you could use the general form:
    // a flag to indicate validity of input
    boolean inputValid = false;
    while ( !inputValid )
    {
        // prompt for and get input from user
     
        // if input is valid, set flag so that loop exits
        if ( a condition that is true if user input is valid )
        {
            inputValid = true;
        }
        else
        {
            // inform the user the input in incorrect
        }
    }

  3. #3
    Junior Member
    Join Date
    Sep 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How do I loop with an If statement

    Thanks for the response. I actually took a second look at the do loop. I did some trial and error and ended up with this. It works. The only thing is, when the user is prompted for the y/n? The input of y or n goes below the input line and I would like it to be on the same line right after the semi colon. Any one know how I can adjust that.

    package assignment2b;
     
    import java.util.Scanner;
     
     
    public class Assignment2b {
     
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
     
        Scanner in = new Scanner(System.in); // input object
     
     
     
        double loanAmount;                                      // user input
        double interestRate;                                    // user input
        double yearNumber;                                      // user input
        double monthlyPayment;                                  // payment from math.pow
        double finalPayment;                                    // actual payment displayed
        double monthNumber;                                     // number of months
        double monthlyRate;                                     // interest rate by month
     
        String answer = null;                                   // string answer
     
        do {                                                    // opens loop        
     
        System.out.print("Enter loan amount: ");                // Line to input loan amount
        loanAmount = Double.parseDouble (in.nextLine());        // Gets input number
     
     
        System.out.print("Enter rate: ");                       // Line to input rate amount
        interestRate = Double.parseDouble (in.nextLine());      // Gets input number
     
        monthlyRate  = interestRate /100 /12;                   //Convert rate into decimals
     
     
        System.out.print("Enter number years: ");               // Line to input number of years
        yearNumber = Double.parseDouble (in.nextLine());        // Gets input number
     
        monthNumber = yearNumber * 12;                          // Total amount of months  
     
        monthlyPayment = Math.pow(1+monthlyRate , monthNumber) / (Math.pow(1+monthlyRate, monthNumber)-1);
     
        finalPayment = (loanAmount*monthlyRate*monthlyPayment);               // Gives the payment          
     
        if (loanAmount <= 0 || interestRate <=0 || yearNumber <=0)            // incorrect# line
         {       
          System.out.println("\nYou must enter positive numeric data!");
     
        }
        else                                                                  // correct# line
        {    
        System.out.printf("\nThe monthly payment is: $%.2f", finalPayment);   // Monthly payment
        System.out.println();                                                 // Moves build line
        } 
     
         System.out.println("\nWould you like to calculate again (y/n): ");   // prompt to run again
          answer = in.nextLine();                                             // gets answer
        }
        while (answer.equals("y"));                                           // runs program again
     
        }
     
     
        }

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: How do I loop with an If statement

    println() will add a linefeed at the end of the prompt line. If you don't want the linefeed, use the print() method.

  5. #5
    Junior Member
    Join Date
    Sep 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How do I loop with an If statement

    Quote Originally Posted by GregBrannon View Post
    println() will add a linefeed at the end of the prompt line. If you don't want the linefeed, use the print() method.
    Sorry still learning. Do you have any example?

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: How do I loop with an If statement

    My memory is fuzzy on exactly which line needs to be modified, so for the line after which a linefeed is not desired, change println() to print(), and you'll have constructed your very own example.

  7. #7
    Junior Member
    Join Date
    Sep 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How do I loop with an If statement

    Quote Originally Posted by GregBrannon View Post
    My memory is fuzzy on exactly which line needs to be modified, so for the line after which a linefeed is not desired, change println() to print(), and you'll have constructed your very own example.
    I've tried this every way I can think of, and I cant the answer to (y/n) to appear on the same line right after the : of the question.

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: How do I loop with an If statement

    Show the code changes you made for the failed attempt(s). You don't have to show every way you can think of, but the one you think is the best would be nice.

  9. #9
    Junior Member
    Join Date
    Sep 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How do I loop with an If statement

    Quote Originally Posted by GregBrannon View Post
    Show the code changes you made for the failed attempt(s). You don't have to show every way you can think of, but the one you think is the best would be nice.
    Got it! Thanks!

  10. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: How do I loop with an If statement

    You fixed it then?

  11. #11
    Junior Member
    Join Date
    Sep 2014
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How do I loop with an If statement

    Quote Originally Posted by GregBrannon View Post
    You fixed it then?
    Yep must have been the computer or Netbeans. I tried the System.out.print() again on a different computer and it worked fine. Very frustrating, I knew that was how to do it.

Similar Threads

  1. How do I loop a switch Statement?
    By Arkeshen in forum Java Theory & Questions
    Replies: 10
    Last Post: August 2nd, 2018, 07:47 AM
  2. [SOLVED] changing for loop to while statement..
    By stanfordjava in forum What's Wrong With My Code?
    Replies: 3
    Last Post: August 24th, 2014, 02:47 AM
  3. [SOLVED] A Loop statement and a switch statement issue
    By sternfox in forum Loops & Control Statements
    Replies: 13
    Last Post: March 7th, 2013, 04:19 PM
  4. Having trouble with for loop statement.
    By Truck35 in forum Loops & Control Statements
    Replies: 3
    Last Post: November 25th, 2012, 04:45 PM
  5. How do I loop this if statement?
    By dunnage888 in forum Loops & Control Statements
    Replies: 5
    Last Post: February 10th, 2012, 12:16 PM