If statement to validate user input

based on user input; declared variables will receive fixed values

Page 1 of 1

9 Replies - 16137 Views - Last Post: 25 April 2010 - 07:54 AM Rate Topic: -----

#1 JoeJo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 23-April 10

If statement to validate user input

Posted 24 April 2010 - 02:35 PM

Hi

I am writing a program that will ask the user for two things:
1. a sum of money
2. an option (they will choose by typing a letter)

the beginning of my program is as follows:

import java.io.*; // import the java io package

public class MortgageCalculator {

   public static void main ( String [] args ) throws IOException //throws exceptions

    {
           BufferedReader stdin =  new BufferedReader(new InputStreamReader( System.in ));

			double Loanprinciple;
			double Annualrate = 0.0;
			int Years;
			double Monthlypayment;
			char A;
			char B;



next I have a block of code which will prompt the user to enter their preference either A or B then if the user enters A; then Annualrate and Years get specific values assigned to them, if they choose B Annualrate and Years get different values.

the code i am tryin to accomplish this with is as follows:

System.out.print( "Enter your option" );
input   =   stdin.readLine();
if(char = A){
  AnnualRate = 5.75;
  Years = 30;
}else if(char = B)/>{
  AnnualRate = 7.4;
  Years = 15;
}        



the 2 errors i am getting are

MortgageCalculator.java:33: '.class' expected
           if(char = A){
                   ^
MortgageCalculator.java:36: '.class' expected
			  }else if(char = B)/>{
			                ^



I am new to writing if statements in Java.

Is This A Good Question/Topic? 0
  • +

Replies To: If statement to validate user input

#2 openoutcome  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 51
  • Joined: 06-November 09

Re: If statement to validate user input

Posted 24 April 2010 - 02:47 PM

First of all, when comparing values, you use the double equals.

if(x == y)


A single equals sign is for assigning values..

x = 100;


Also, Why don't you use a scanner for user input? http://java.sun.com/...il/Scanner.html

Hope this helps!
Was This Post Helpful? 1
  • +
  • -

#3 zim1985  Icon User is offline

  • Grand Inquisitor
  • member icon

Reputation: 74
  • View blog
  • Posts: 568
  • Joined: 19-February 10

Re: If statement to validate user input

Posted 24 April 2010 - 02:59 PM

As the above said, you need to use the double "=" to test for equality.
int x = 2;  // = assigns value
int y = 3;
if(x == y) // == test for equality (a boolean statement)
{
    System.out.println("Equal");
}


That other thing you are doing wrong is where you are testing for a char. Chars are written with single quotes around them. The way you have it, the Java Compiler is looking for some object named A. Look at this:
// declare a char
char letter = 'a'; // notice single quotes
char num = 97; // you can also declare as numbers


Notice how you declare a char. You can declare them as the actual letter with single quotes or, because all characters have an integer ASCII value assigned to them, you can initialize them as a number. The first form works in the majority of situations, though when working with special characters that aren't easily typed on your keyboard, the number values work as well.
Was This Post Helpful? 0
  • +
  • -

#4 JoeJo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 23-April 10

Re: If statement to validate user input

Posted 24 April 2010 - 05:12 PM

Thanks that cleared it up The program is running but; it gives the same answer regardless of the letter. Then i took a closer look and realized that I can have a variable with 2 different values unless its an array. so once i gave A, B and C a different variable name; everything worked. here is the working code. thanks again.
import java.io.*; // import the java io package

public class MortgageCalculator {

   public static void main ( String [] args ) throws IOException //throws exceptions

    {
           BufferedReader stdin =  new BufferedReader(new InputStreamReader( System.in ));

			double Loanprinciple;
			double Annualrate = 0.0;
			int Years = 0;
			double Monthlypayment;
			char letter = 'A';
			char letter2 = 'B';
			char letter3 = 'C';
					
           System.out.print("Enter a Loan Amount:");
           String input   =   stdin.readLine();             //get Loan Amount
           Loanprinciple    =   Double.parseDouble( input );

           System.out.print("Enter A,B or C:");
           input   =   stdin.readLine();                      //get Interest Rate
           if(letter=='A'){
			  		Annualrate = 5.35;
					Years = 7;
			  }else if(letter2=='B'){
			  		Annualrate = 5.5;
					Years = 15;
			  }else if(letter3=='C'){
			  		Annualrate = 5.75;
					Years = 30;
			  }
			 

           double Rate = Annualrate/100;
           double Monthlyrate = Rate/12;
           int Months = Years * 12;

           Monthlypayment = Loanprinciple * ( Monthlyrate / ( 1 - Math.pow( ( 1 + Monthlyrate ) , ( -1 * Months ) ) ) );

            System.out.printf("Your monthly payment will be: $ %.2f", Monthlypayment);
            System.out.println("");

    }
    }



This post has been edited by JoeJo: 24 April 2010 - 05:25 PM

Was This Post Helpful? 0
  • +
  • -

#5 openoutcome  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 51
  • Joined: 06-November 09

Re: If statement to validate user input

Posted 24 April 2010 - 05:24 PM

Check this part out:

System.out.print("Enter A,B or C:");
           input   =   stdin.readLine();   


See what variable you are putting user input into?

Now look at what you are comparing with:

if(letter=='A')
else if(letter=='B')
else if(letter=='C')


Once you get that straightened out, you'll want to add some user input validation. What if the user types D instead? Or a number? Or lower-case: a, b, or c.

Good job so far!~ :smartass:
Was This Post Helpful? 0
  • +
  • -

#6 JoeJo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 23-April 10

Re: If statement to validate user input

Posted 24 April 2010 - 06:09 PM

I want to add more information; an amortization table to be specific. So for example if the user enters C the number of years is 30 and that is 360 months so the program should show a table listing The Monthly Payment, Remaining Balance and Interest Paid for 360.

The program compiles but after the amortization table heading it goes into error.

the program

import java.io.*; // import the java io package

public class MortgageCalculator {

   public static void main ( String [] args ) throws IOException //throws exceptions

    {
           BufferedReader stdin =  new BufferedReader(new InputStreamReader( System.in ));

			double Loanprincipal;
			double Annualrate = 0.0;
			int Years = 0;
			double Monthlypayment;
			char letter = 'A';
			char letter2 = 'B';
			char letter3 = 'C';
			double Principal = 0;
								
           System.out.print("Enter a Loan Amount:");
           String input   =   stdin.readLine();             //get Loan Amount
           Loanprincipal    =   Double.parseDouble( input );

           System.out.print("Enter A,B or C:");
           input   =   stdin.readLine();                      //get Interest Rate
           if(letter=='A'){
			  		Annualrate = 5.35;
					Years = 7;
			  }else if(letter2=='B'){
			  		Annualrate = 5.5;
					Years = 15;
			  }else if(letter3=='C'){
			  		Annualrate = 5.75;
					Years = 30;
			  }
			 

           double Rate = Annualrate/100;
           double Monthlyrate = Rate/12;
           int Months = Years * 12;

           Monthlypayment = Loanprincipal * ( Monthlyrate / ( 1 - Math.pow( ( 1 + Monthlyrate ) , ( -1 * Months ) ) ) );

            System.out.printf("Your monthly payment will be: $ %.2f", Monthlypayment);
            System.out.println("");
				
				// Amoritization Table Header
		      System.out.printf("\n\n\n\t\t\t\tMortgage Amoritization Table\n\n");

				// Amoritization Table Column Headings
			   System.out.printf("Month No.\t\tMonthly Payment\t\tRemaining Balance\t\tInterest Paid\n");

           	// set remaining balance to the original loan principle
            double OutstandingBalance = Principal;
				// loop through months in the loan plan
			   for(int x = 1; x<= Months; x++){
            double CurrentPaymentInterest = Monthlyrate * OutstandingBalance; // calculate interest for current payment
				double CurrentPaymentPrincipal = Months - CurrentPaymentInterest; // calculate the principle for current payment
				OutstandingBalance = OutstandingBalance - CurrentPaymentPrincipal; // calculate the total remaining balance

			// Outputs the monthly amounts to the screen under their Amoritization Table Headings
			System.out.printf("%3d\t\t\t%.2f\t\t\t%.2f\t\t\t%.2f\n",x , Months , OutstandingBalance , CurrentPaymentInterest);

			// loop to break after every 50th row and asks user to press enter to continue
			if(x % 50 == 0){
				String TempHolder = null;
				System.out.printf("Press the ENTER key to continue...");
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
					try{
						TempHolder = br.readLine();
					} catch(IOException e){
						System.out.println("There has been an error");
						System.exit(1);
							}
						}
					}

				
				}
}
	
			
    




the error reported

Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.Integer
	at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:3999)
	at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2722)
	at java.util.Formatter$FormatSpecifier.print(Formatter.java:2667)
	at java.util.Formatter.format(Formatter.java:2433)
	at java.io.PrintStream.format(PrintStream.java:920)
	at java.io.PrintStream.printf(PrintStream.java:821)
	at MortgageCalculator.main(MortgageCalculator.java:72)



what does the error mean and how is it solved; does this mean that the formulas for the remaining balance and the balance paid are wrong?
Was This Post Helpful? 0
  • +
  • -

#7 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10563
  • View blog
  • Posts: 39,087
  • Joined: 27-December 08

Re: If statement to validate user input

Posted 24 April 2010 - 06:39 PM

Your second formatter, the %.2f matches up with the variable Months, which is an int. Remember that the %f formatter is used for floating-point numbers (doubles and floats), not integers. So if you want an integer there, use the %d formatter for decimal (base-10) numbers instead.
System.out.printf("%3d\t\t\t%.2f\t\t\t%.2f\t\t\t%.2f\n",x , Months , OutstandingBalance , CurrentPaymentInterest); 


Was This Post Helpful? 0
  • +
  • -

#8 JoeJo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 23-April 10

Re: If statement to validate user input

Posted 25 April 2010 - 07:22 AM

Thank you, i had to do the following

if(letter=='A')
else if(letter2=='B')
else if(letter3=='C')


Was This Post Helpful? 0
  • +
  • -

#9 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1010
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: If statement to validate user input

Posted 25 April 2010 - 07:32 AM

I spotted a logic problem you have in your code.
letter is initialized to 'A', letter2 initialized to 'B' and letter3 initialized to 'C', as you declare these variables:
char letter = 'A'; 
char letter2 = 'B'; 
char letter3 = 'C';

if these variables are declared so, i see no point in that if\else statements, as they will always return true:
if(letter=='A'){ 
    Annualrate = 5.35; 
    Years = 7; 
}
else if(letter2=='B'){ 
    Annualrate = 5.5; 
    Years = 15; 
}else if(letter3=='C'){ 
    Annualrate = 5.75; 
    Years = 30; 
} 

Also, since you always update the same 2 variables: Annualrate and Years, their values will always be the last value you assign them (which is inside the last else if statement).
in other words, the value of Annualrate will always be 5.75, and Years will always be 30.

I believe you want to pass the user input into the letter variable, as:
letter = input.charAt(0);

then, only compare the value in letter (no need to use letter2 and letter3) as:
if(letter=='A'){ 
    Annualrate = 5.35; 
    Years = 7; 
}
else if(letter=='B'){ 
    Annualrate = 5.5; 
    Years = 15; 
}else if(letter=='C'){ 
    Annualrate = 5.75; 
    Years = 30; 
} 

Was This Post Helpful? 0
  • +
  • -

#10 JoeJo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 23-April 10

Re: If statement to validate user input

Posted 25 April 2010 - 07:54 AM

i changed months declaration from an
int
to a
double
and that work.
I think something is wrong with my loop for the recursion through the months

A = 7 yrs = 84 months
B = 15 yrs = 180 months
C = 30 yrs = 360 months

I not sure if my code just needs compiling properly. I am using JGrasp.

can someone run my prg & tell me if it is working for them.

import java.io.*; // import the java io package
import java.util.*;

public class MortgageCalculator {

   public static void main ( String [] args ) throws IOException //throws exceptions

    {
           BufferedReader stdin =  new BufferedReader(new InputStreamReader( System.in ));

			double Loanprincipal;
			double Annualrate = 0.0;
			int Years = 0;
			double Monthlypayment;
			char letter = 'A';
			char letter2 = 'B';
			char letter3 = 'C';
									
           System.out.print("Enter a Loan Amount:");
           String input   =   stdin.readLine();             //get Loan Amount
           Loanprincipal    =   Double.parseDouble( input );

           System.out.print("Enter A,B or C:");
           input   =   stdin.readLine();                      //get user option
           if(letter=='A'){
			  		Annualrate = 5.35;
					Years = 7;
			  }if(letter2=='B'){
			  		Annualrate = 5.05;
					Years = 15;
			  }if(letter3=='C'){
			  		Annualrate = 5.75;
					Years = 30;
			  }
			 

           double Rate = Annualrate/100;
           double Monthlyrate = Rate/12;
           double Months = Years * 12;

           Monthlypayment = Loanprincipal * ( Monthlyrate / ( 1 - Math.pow( ( 1 + Monthlyrate ) , ( -1 * Months ) ) ) );

            System.out.printf("Your monthly payment will be: $ %.2f", Monthlypayment);
            System.out.println("");
				
				// Amoritization Table Header
		      System.out.printf("\n\n\n\t\t\t\tMortgage Amoritization Table\n\n");

				// Amoritization Table Column Headings
			   System.out.printf("Month No.\t\tMonthly Payment\t\tRemaining Balance\t\tInterest Paid\n");

           	// set remaining balance to the original loan principle
            double OutstandingBalance = Loanprincipal;
				// loop through months in the loan plan
			   for(int y=0; y<=Months; y++){
            double CurrentPaymentInterest = Monthlyrate * OutstandingBalance; // calculate interest for current payment
				double CurrentPaymentPrincipal = Months - CurrentPaymentInterest; // calculate the principle for current payment
				OutstandingBalance = OutstandingBalance - CurrentPaymentPrincipal; // calculate the total remaining balance

				// Outputs the monthly amounts to the screen under their Amoritization Table Headings
				System.out.printf("%3d\t\t\t%.2f\t\t\t%.2f\t\t\t%.2f\n", y , Months , OutstandingBalance , CurrentPaymentInterest);

				// loop to break after every 50th row and asks user to press enter to continue
				if(y % 50 == 0){
				String TempHolder = null;
				System.out.printf("Press the ENTER key to continue...");
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
					try{
						TempHolder = br.readLine();
					} catch(IOException e){
						System.out.println("There has been an error");
						System.exit(1);
							}
						}
					}

				
				}
}
	
			
    



Was This Post Helpful? 0
  • +
  • -

Page 1 of 1