Skips over system out, scan nextLine, and if loops - java

New here (and to Java!). I've searched around the site for an answer to my problem but came up naught. This program executes up to the scan.nextDouble statement.
If I enter a salary value such as "8," I get:
/////OUTPUT/////
Enter the performance rating (Excellent, Good, or Poor):
Current Salary: $8.00
Amount of your raise: $0.00
Your new salary: $8.00
/////END OF OUTPUT/////
So obviously, my following scan.nextLine and all the if-else statements are bypassed. What am I missing?
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary
{
public static void main(String[] args)
{
double currentSalary; // employee's current salary
double raise = 0; // amount of the raise
double newSalary = 0; // new salary for the employee
String rating; // performance rating
String rating1 = new String("Excellent");
String rating2 = new String("Good");
String rating3 = new String("Poor");
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.nextLine();
// Compute the raise using if ...
if (rating.equals(rating1))
raise = .06;
else
if (rating.equals(rating2))
raise = .04;
else
if (rating.equals(rating3))
raise = .015;
else
newSalary = currentSalary + currentSalary * raise;
// Print the results
{
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
}

When you scan input using scanner.nextDouble() it takes only the float value and leaves the new line character in the buffer so after that when you do scanner.nextLine(() it takes the new line character and returns empty string.Put another scanner.nextLine() before scanning the next line to eat up the new line character
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
scan.nextLine();
rating = scan.nextLine();

Scanner.nextDouble() just reads the next available double value and does not by itself point to next line.
use a dummy scanner.nextLine() before your actual one. that lets your cursor point to next line from which your scanner.nextline() takes the input.
-cheers :)

Related

Capitalize Name in output of ArrayLists in Java

I am relatively fresh (couple weeks) into Java and I am messing around with an Employee input system with ArrayLists. Anyway I want to ensure no matter the user input that that name in the output is the same format.
Example:
Input --> Enter Employee Name: SAMANTHA
Output --> Employee Name: Samantha
Here is the code I am running, I am just not sure where within this I could set that formatting.
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeTester_v5
{
public static void main (String[] args)
{
//ASSIGN VARIABLES
String c = "";
String newEmployee = "";
double yearToDate = 0.0;
double increase = 0.025;
double newSalary = 0.0;
//ARRAY LISTS
ArrayList<String>first = new ArrayList<String>();
ArrayList<String>last = new ArrayList<String>();
ArrayList<Double>salary = new ArrayList<Double>();
ArrayList<Integer>months = new ArrayList<Integer>();
//SCANNER INPUT
//create a new scanner
Scanner input = new Scanner(System.in);
//WHILE LOOP - to keep asking for user input until "No" is entered
do{
//USER INPUT
System.out.println ("Enter employee first name: ");
first.add(input.next());
System.out.println ("Enter employee last name: ");
last.add(input.next());
System.out.println ("Enter employee salary: ");
salary.add(input.nextDouble());
System.out.println ("Number of months worked this year: ");
months.add(input.nextInt());
System.out.println("Enter another employee in the system?");
c = input.next();
}while(c.equalsIgnoreCase("Yes"));
System.out.println();
//ARRAY OUTPUT
for(int i=0; i < first.size(); i++)
{
yearToDate = months.get(i) * salary.get(i)/12;
newSalary = (increase * salary.get(i)) + salary.get(i);
System.out.print("Employee Name: " + first.get(i) + " ");
System.out.print(last.get(i)+"\n");
System.out.printf("Current Salary: $%.2f\n", salary.get(i));
System.out.printf("Year to Date: $%.2f\n", yearToDate);
System.out.printf("New Salary: $%.2f\n", newSalary);
System.out.println("----------------------");
}
}
}
First thing you should do is to check out String API https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
It's a must-know when it comes to Java, you'll need it in possibly every project you'll work on :)
There are plenty of ways to achieve your goal here.
What you could do for example is to capitalize the first letter and then append the rest of the String that you'll force to lowercase - check out the snippet below.
String inputString = input.next();
String resultString = inputString.substring(0, 1).toUpperCase() + inputString.substring(1).toLowerCase();
Try like this :
System.out.print("Employee Name: " + first.get(i).substring(0,1).toUpperCase()+first.get(i).substring(1).toLowerCase() + " ");
this one first.get(i).substring(0,1).toUpperCase() gest your first letter in string upper, and first.get(i).substring(1).toLowerCase() gets letters from index 1 - so from the 2nd letter of the string to lower.
Maybe what the OP is not understanding, is that this can be wrapped in a private method, like this:
private String fixCapitalisation(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
}
Then your line uses this by adjusting the line that prints the name:
System.out.print("Employee Name: " + fixCapitalisation(first.get(i)) + " ");
You can then reuse this function on the last name too...
Here is the entire class with this change:
package Dunno;
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeTester_v5
{
public static void main (String[] args)
{
//ASSIGN VARIABLES
String c = "";
String newEmployee = "";
double yearToDate = 0.0;
double increase = 0.025;
double newSalary = 0.0;
//ARRAY LISTS
ArrayList<String>first = new ArrayList<String>();
ArrayList<String>last = new ArrayList<String>();
ArrayList<Double>salary = new ArrayList<Double>();
ArrayList<Integer>months = new ArrayList<Integer>();
//SCANNER INPUT
//create a new scanner
Scanner input = new Scanner(System.in);
//WHILE LOOP - to keep asking for user input until "No" is entered
do{
//USER INPUT
System.out.println ("Enter employee first name: ");
first.add(input.next());
System.out.println ("Enter employee last name: ");
last.add(input.next());
System.out.println ("Enter employee salary: ");
salary.add(input.nextDouble());
System.out.println ("Number of months worked this year: ");
months.add(input.nextInt());
System.out.println("Enter another employee in the system?");
c = input.next();
}while(c.equalsIgnoreCase("Yes"));
System.out.println();
//ARRAY OUTPUT
for(int i=0; i < first.size(); i++)
{
yearToDate = months.get(i) * salary.get(i)/12;
newSalary = (increase * salary.get(i)) + salary.get(i);
System.out.print("Employee Name: " + fixCapitalisation(first.get(i)) + " ");
System.out.print(last.get(i)+"\n");
System.out.printf("Current Salary: $%.2f\n", salary.get(i));
System.out.printf("Year to Date: $%.2f\n", yearToDate);
System.out.printf("New Salary: $%.2f\n", newSalary);
System.out.println("----------------------");
}
}
//New Method to fix capitalisation
private static String fixCapitalisation(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
}
I hope my answer might help you to understand the answers already given better, and how the duplicate answer i provided is relevant - the use of an ArrayList here makes no difference to the String manipulation.
You should consider defining your own class of "Employee", that can persist the name, salary etc. then you only need one ArrayList, you currently have lists with values that are Logically linked by their position in the Array, but there is no technical dependency on that.

Delete one scanner, Payroll program Week 3 [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 7 years ago.
How am I able to get rid of one scanner? If I do use just one scanner the after the weekly_pay is output is:
Employee Name
Enter the hours worked for the week.
The program skips right over asking for the employee name variable. With both scanners it does indeed loop asking for the employee name as it should.
//Week 3 Assignment
package weeklypay2;
import java.util.Scanner; // importing the Java utility class scanner
public class WeeklyPay2 // class WeeklyPay
{
//main method
public static void main(String[] args)
{
Scanner Scanner = new Scanner(System.in);
Scanner Scanner1 = new Scanner(System.in);
String employee_name = null; // variable for employee name
double hours_worked = 0, // variable for weekly hours worked
pay_rate = 0, // variable for pay rate per hour
weekly_pay = 0; // weekly pay = hours * pay_rate
while (employee_name!="stop")
{
System.out.println("");
System.out.println("Employee Name"); // prompt, employees name
employee_name = Scanner1.nextLine();
if (employee_name.equalsIgnoreCase("stop"))
{
System.out.print("Exiting Program");
break;
} // ends if statement
else
{
System.out.println("Enter the hours worked for the week");
//prompt, hours worked for the current week
pay_rate = Scanner.nextDouble();
while(pay_rate < 0.01)
{
System.out.print("ERROR!!, Input a postive number: \n");
pay_rate = Scanner.nextDouble();
}
System.out.println("Enter the employees hourly pay rate");
// prompt, the employees pay rate
hours_worked = Scanner.nextDouble();
while(hours_worked < 0.01)
{
System.out.print("ERROR!!, Input a postive number: \n");
hours_worked = Scanner.nextDouble();
}
weekly_pay = (double) hours_worked * (double) pay_rate; // setting the variable weekly_pay
System.out.println(employee_name + "'s weekly pay is $" + weekly_pay ); // output the employees name and weekly pay
}
}
Scanner.close();
Scanner1.close();
} //ends main method
} //ends class WeeklyPay
Well the first thing I would say is be careful naming your scanner. Don't start that with a capital. Now a big thing is you don't want to compare strings using !=, this is not intended for string variables. There is a fun method for comparing strings that would be .equals() or .equalsIgnoreCase() depending if you want it non-case sensitive. Now after changing those few things in your code it works just fine. Also just a heads up Java also includes a method for formatting currency. You're pay numbers were missing a decimal. If you look at the NumberFormat I added after the scanner and then look at the println at the end you can see its very simple to use.
import java.text.NumberFormat;
import java.util.Scanner; // importing the Java utility class scanner
public class WeeklyPay2 // class WeeklyPay
{
//main method
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
NumberFormat format = NumberFormat.getCurrencyInstance();
String employee_name = "";
double hours_worked = 0, // variable for weekly hours worked
pay_rate = 0, // variable for pay rate per hour
weekly_pay = 0; // weekly pay = hours * pay_rate
while (!employee_name.equalsIgnoreCase("stop"))
{
System.out.println();
System.out.print("Employee Name: ");
employee_name = scanner.nextLine();
if (employee_name.equalsIgnoreCase("stop"))
{
System.out.print("Exiting Program");
break;
} // ends if statement
else
{
System.out.print("Enter the hours worked for the week: ");
//prompt, hours worked for the current week
pay_rate = scanner.nextDouble();
while(pay_rate < 0.01)
{
System.out.print("ERROR!!, Input a postive number: ");
pay_rate = scanner.nextDouble();
}
System.out.print("Enter the employees hourly pay rate: ");
// prompt, the employees pay rate
hours_worked = scanner.nextDouble();
while(hours_worked < 0.01)
{
System.out.print("ERROR!!, Input a postive number: \n");
hours_worked = scanner.nextDouble();
}
weekly_pay = (double) hours_worked * (double) pay_rate; // setting the variable weekly_pay
System.out.println(employee_name + "'s weekly pay is: " + format.format(weekly_pay)); // output the employees name and weekly pay
scanner.nextLine();
}
}
scanner.close();
} //ends main method
} //ends class WeeklyPay
And this is the output we would see:
Oh, PS: Keep the program cleaner by prompting for the input on the same line, more intuitive and better to look at. By all means add a line break after the input but not before :)
use Scanner1.nextLine() after getting the value for hours worked.
Refer modified code below:
import java.util.Scanner; // importing the Java utility class scanner
public class WeeklyPay2 // class WeeklyPay
{
//main method
public static void main(String[] args) {
Scanner Scanner1 = new Scanner(System.in);
String employee_name = null; // variable for employee name
double hours_worked = 0, // variable for weekly hours worked
pay_rate = 0, // variable for pay rate per hour
weekly_pay = 0; // weekly pay = hours * pay_rate
//Scanner1.useDelimiter("//n");
while (true) {
System.out.println("");
System.out.println("Employee Name"); // prompt, employees name
employee_name = Scanner1.nextLine();
if (employee_name.equalsIgnoreCase("stop"))
{
System.out.print("Exiting Program");
break;
}// ends if statement
else {
System.out.println("Enter the hours worked for the week");
//prompt, hours worked for the current week
pay_rate = Scanner1.nextDouble();
while (pay_rate < 0.01) {
System.out.print("ERROR!!, Input a postive number: \n");
pay_rate = Scanner1.nextDouble();
}
System.out.println("Enter the employees hourly pay rate");
// prompt, the employees pay rate
hours_worked = Scanner1.nextDouble();
while (hours_worked < 0.01) {
System.out.print("ERROR!!, Input a postive number: \n");
hours_worked = Scanner1.nextDouble();
//Scanner1.
}
Scanner1.nextLine();
weekly_pay = (double) hours_worked * (double)
pay_rate; // setting the variable weekly_pay
System.out.println(employee_name + "'s weekly pay is $" + weekly_pay); // output the employees name and weekly pay
}
}
Scanner1.close();
} //ends main method
}//ends class WeeklyPay

Anyone know why these if else statement wont work?

public class Salary
{
public static void main (String[] args)
{
double currentSalary; // employee's current salary
double raise; // amount of the raise
double percentRaise; // percentage of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
if (rating.equals("Excellent"))
percentRaise = .06;
raise = (.06 * currentSalary);
else if (rating.equals("Good"))
percentRaise = .04;
raise = (.04 * currentSalary);
else if (rating.equals("Poor"))
percentRaise = .015;
raise = (.015 * currentSalary);
//Compute the raise using if ...
newSalary = currentSalary + raise;
//Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println( "Your new salary: " + money. format (newSalary) );
System.out.println();
scan.close();
}
}
if i add { and } where the whitespace is then it says raise is not initialized. No matter what i do i cant seem to figure out to get it running. Right now it tells me to delete the else to let it run but if i do no matter i write excellent, good, or poor. It does .015 * salary so i cant get excellent or good to run.
if (rating.equals("Excellent"))
percentRaise = .06;
raise = (.06 * currentSalary);
else if (rating.equals("Good"))
Won't compile because Java sees this as...
if (rating.equals("Excellent"))
percentRaise = .06;
raise = (.06 * currentSalary);
else if (rating.equals("Good"))
Meaning that the compiler will complain about the else-if without a if statement.
The other problem you're having (when you place { } around the statements) is because Java makes no determination about what the initial value of a local variable will have.
This means Java simply doesn't know what to do with newSalary = currentSalary + raise; as there is no guarantee that raise will have a value assigned to it.
You could overcome this by adding an else condition to the end of your if-else block or simply supplying an initial value to your local variables...
double currentSalary = 0; // employee's current salary
double raise = 0; // amount of the raise
double percentRaise = 0; // percentage of the raise
double newSalary = 0; // new salary for the employee
String rating = ""; // performance rating
And while it might seem annoying, it's better then getting some completely random value which you would have to spend time trying to debug ;)
Updated
Remember, String#equals is case sensitive, this means "Excellent" is not equal to "excellent".
You could use String#equalsIgnoreCase instead
You need to wrap if statements into these things ---> "{}"
so its like this:
if(statement){
//then do someting
}else{
//then do something else
}
You can only write if statements without braces if it contains only one command, if you have more than one command (more than one line) you need to enclose those commands in braces
You have to make sure that if your if statement contains more than one line of code, it is wrapped in braces.
public class Salary
{
public static void main (String[] args)
{
double currentSalary; // employee's current salary
double raise; // amount of the raise
double percentRaise; // percentage of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
if (rating.equals("Excellent"))
{
percentRaise = .06;
raise = (.06 * currentSalary);
}
else if (rating.equals("Good"))
{
percentRaise = .04;
raise = (.04 * currentSalary);
}
else if (rating.equals("Poor"))
{
percentRaise = .015;
raise = (.015 * currentSalary);
}
//Compute the raise using if ...
newSalary = currentSalary + raise;
//Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println( "Your new salary: " + money. format (newSalary) );
System.out.println();
scan.close();
}
}

Writing for loops/while loops?

I'm in a programming class in high-school, and I was given an assignment to make a basic subtotal and top calculator, but I work at a restaurant, so it seemed a little pointless to make a calculator that only let you read in one food. So I tried to make it able to take in multiple food items and add them to one price variable. Sorry if some of this code may seem inefficient or redundant. It's only high-school of course.
The issue is, when I run it, it gets up to the asking if there was another food item the user would like to add, and when I type in "Yes" or "No", the program does nothing. Keeps running, but goes no further. Any explanations?
import java.text.NumberFormat;
import java.util.Scanner;
public class Price {
/**
* #param args
*/
public static void main(String[] args) {
final double taxRate = .0887; //8.87% Tax Rate
double tipRate;
int quantity1;
Scanner kb = new Scanner(System.in);
double subtotal, tax, tip, totalCost1, unitPrice1 = 0;
String done;
System.out.println ("How many of the first item did you get?: ");
quantity1 = kb.nextInt();
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
while (done.equalsIgnoreCase("Yes"));
}
System.out.println ("What percent would you like to tip? (Formatted like 0.10 for 10%, 0.20 for 20%, etc.): ");
tipRate = kb.nextDouble();
subtotal= quantity1 * unitPrice1;
tax = subtotal * taxRate;
totalCost1 = subtotal + tax;
tip = totalCost1 * tipRate;
totalCost1 = totalCost1 + tip;
//Formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
NumberFormat tipMoney = NumberFormat.getCurrencyInstance();
NumberFormat taxPercent = NumberFormat.getPercentInstance();
NumberFormat tipPercent = NumberFormat.getPercentInstance();
System.out.println ("Your total before tax is: " + money.format(subtotal));
System.out.println ("The tax is " + money.format(tax) + " at " + tipPercent.format(taxRate));
System.out.println ("The tip at " + tipPercent.format(tipRate) + " is " + tipMoney.format(tip));
}
}
You have an infinite loop here:
while (done.equalsIgnoreCase("Yes"));
Once you enter Yes, it will keep sitting there and doing nothing because the value of done is Yes and never changes.
Also your loop structure is a bit odd. Your outer for loop runs as many times as the quantity of the first item. But shouldn't you only be multiplying that number to the cost? Because you are either running the loop for as long as the number of items the user entered (by asking them up front) or you don't ask them the total number of items and simply ask them to enter Yes if they want to add more items; you can't really do both.
Your loop should probably look something like this:
String input = "Yes";
while(input.equalsIgnoreCase("Yes")) {
System.out.println ("How many of the first item did you get? ");
quantity1 = kb.nextInt();
System.out.println ("What was the price of that single item? ");
unitPrice1 = kb.nextDouble();
//total += unitPrice1 * quantity1 - you don't have this in your code, but this is where you would be calculating the running total
System.out.println("Was there another food item you'd like to add? ");
input = kb.next();
}
you need to exit for loop when user enters yes, so you can use label here like below:
outerloop:
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
while (done.equalsIgnoreCase("Yes")){
break outerloop;
}
}
Your current code does not do anything inside the while loop if you don't enter yes. And if you enter yes it will be stuck in infinite loop because of your while loop. This is not the efficeint way of looping, but this code will have least change in your current code.
You're while loop is doing nothing, you had given it a condition, but it has no instruction.
Try something like this..(sorry for my rusty java)
'public static void main(String[] args) {
//variable declaration
bool running = true
final double taxRate = .0887; //8.87% Tax Rate
double tipRate;
int quantity1;
Scanner kb = new Scanner(System.in);
double subtotal, tax, tip, totalCost1, unitPrice1 = 0;
String done;
while(running = true){
System.out.println ("How many of the first item did you get?: ");
quantity1 = kb.nextInt();
for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();
System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
if(done.equalsIgnoreCase("No")){
running = false
//Allows you to break out of the while loop if the user does not want to add anything else
//DO NOT USE BREAK STATMENTS, IT IS A POOR PROGRAMMING PRACTICE.
};//end if
}//end for
}//end while
System.out.println ("What percent would you like to tip? (Formatted like 0.10 for 10%, 0.20 for 20%, etc.): ");
tipRate = kb.nextDouble();
//You should comment whats going on here
subtotal= quantity1 * unitPrice1;
tax = subtotal * taxRate;
totalCost1 = subtotal + tax;
tip = totalCost1 * tipRate;
totalCost1 = totalCost1 + tip;
//Formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
NumberFormat tipMoney = NumberFormat.getCurrencyInstance();
NumberFormat taxPercent = NumberFormat.getPercentInstance();
NumberFormat tipPercent = NumberFormat.getPercentInstance();
//Output
System.out.println ("Your total before tax is: " + money.format(subtotal));
System.out.println ("The tax is " + money.format(tax) + " at " + tipPercent.format(taxRate));
System.out.println ("The tip at " + tipPercent.format(tipRate) + " is " + tipMoney.format(tip));
}//end main

monthly payment calculator

I have some code which I find to keep giving me a dividing by 0 error.
It is suppose to calculate the monthly payment amount!
import java.io.*;
public class Bert
{
public static void main(String[] args)throws IOException
{
//Declaring Variables
int price, downpayment, tradeIn, months,loanAmt, interest;
double annualInterest, payment;
String custName, inputPrice,inputDownPayment,inputTradeIn,inputMonths, inputAnnualInterest;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
//Get Input from User
System.out.println("What is your name? ");
custName = dataIn.readLine();
System.out.print("What is the price of the car? ");
inputPrice = dataIn.readLine();
System.out.print("What is the downpayment? ");
inputDownPayment = dataIn.readLine();
System.out.print("What is the trade-in value? ");
inputTradeIn = dataIn.readLine();
System.out.print("For how many months is the loan? ");
inputMonths = dataIn.readLine();
System.out.print("What is the decimal interest rate? ");
inputAnnualInterest = dataIn.readLine();
//Conversions
price = Integer.parseInt(inputPrice);
downpayment = Integer.parseInt(inputDownPayment);
tradeIn = Integer.parseInt(inputTradeIn);
months = Integer.parseInt(inputMonths);
annualInterest = Double.parseDouble(inputAnnualInterest);
interest =(int)annualInterest/12;
loanAmt = price-downpayment-tradeIn;
//payment = loanAmt*interest/a-(1+interest)
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
//Output
System.out.print("The monthly payment for " + custName + " is $");
System.out.println(payment);
// figures out monthly payment amount!!!
}
}
the problem occurs when attempting to set the payment variable.
i don't understand why it keeps coming up with dividing by 0 error.
You have declared your variables as Int so 1/interest and 1/(interest*Math.pow(1+interest,-months)) will return 0. Change the type of your variables to float or double.
One suggestion to you, is that you should learn to "backwards slice" your code.
This means that when you see that you're getting a DivideByZeroException you should look at your code, and say, "why could this happen?"
In your case, let's look at this:
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
So, now, Math.pow will never return anything zero (as it's a power), so it must be the case that interestis zero. Let's find out why:
interest =(int)annualInterest/12;
So now, integer division in Java truncates. This means that if you have .5 it will be cut off, and turned into zero. (Similarly, 1.3 will be truncated to 0).
So now:
annualInterest = Double.parseDouble(inputAnnualInterest);
This implies that you are passing in something that gets parsed to a value that is less than 12. If it were greater than 12 then you would get something else.
However, you might just be passing in an invalid string, for example, passing in "hello2.0" won't work!
This will be rounding always to 0. So it is trowing exception.
(1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
Use float type instead of int. Learn how they works.
package computeloan;
import java.util.Scanner;
public class ComputeLoan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter Yearly Interest Rate : ");
double annualIntersetRate = input.nextDouble();
double monthlyIntersetRate = annualIntersetRate / 1200;
System.out.print(" Enter Number of years : ");
int numberOfYears = input.nextInt();
// Enter loan amount
System.out.print(" Enter Loan Amount : ");
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyIntersetRate /(1-1/Math.pow(1+monthlyIntersetRate,numberOfYears*12 ));
double totalPayment = monthlyPayment * numberOfYears * 12;
//Calculate monthlyPaymeent and totalPayment
System.out.println(" The Monthly Payment Is : " +(int)(monthlyPayment*100) /100.0);
System.out.println(" The Total Payment Is : " +(int)(totalPayment*100) /100.0 );
}
}

Categories

Resources