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

# Thread: How do I loop with an If statement

1. ## 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
}

}
}```

2. ## 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. ## 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
}
while (answer.equals("y"));                                           // runs program again

}

}```

4. ## 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. ## Re: How do I loop with an If statement

Originally Posted by GregBrannon
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. ## 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. ## Re: How do I loop with an If statement

Originally Posted by GregBrannon
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. ## 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. ## Re: How do I loop with an If statement

Originally Posted by GregBrannon
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. ## Re: How do I loop with an If statement

You fixed it then?

11. ## Re: How do I loop with an If statement

Originally Posted by GregBrannon
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.