Receiving Infinity Value - java

I'm trying to make a unit conversion program but I keep receiving value as infinity. I'm not sure where I need to fix since it's not giving me errors. I only tested oz to ml to make sure I'm doing it correctly but I'm receiving infinity as the answer.
UnitConverter.java:
public class UnitConverter {
final double oz_TO_ml = 29.5735;
final double gal_TO_g = 3.78541;
final double lb_TO_kg = 0.453592;
final double inc_TO_mm = 25.4;//Inc is inches
final double ft_TO_cm = 30.48;
final double mi_TO_km = 1.60934;
double factor;
public UnitConverter(String unit) {
if (unit.equals("oz")) {
factor = oz_TO_ml;
} else if (unit.equals("gal")) {
factor = gal_TO_g;
} else if (unit.equals("lb")) {
factor = lb_TO_kg;
}
}
public double toOz(double amount) {
return (amount * factor);
}
public double fromOz(double amount) {
return (amount / factor);
}
public double toMl(double amount) {
return (amount * factor);
}
public double fromMl(double amount) {
return (amount / factor);
}
}
Calculator.java:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
System.out.print("Value ");
double val = in.nextDouble();
double oz = from.toOz(val);
double converted = to.fromOz(oz);
System.out.println(val + " " + fromUnit + " = " + converted + " " + toUnit);
}
}
Sample input:
Convert from: oz
Convert to: ml
Value 12
Output:
12.0 oz = Infinity ml

Initialize the factor varible with one. A java with default give 0 to primitive double,
class UnitConvertor {
final double oz_TO_ml = 29.5735;
final double gal_TO_g = 3.78541;
final double lb_TO_kg = 0.453592;
final double inc_TO_mm = 25.4;//Inc is inches
final double ft_TO_cm = 30.48;
final double mi_TO_km = 1.60934;
double factor=1;//initialize with 1
But I am still not sure that what is the check you are using if the user input is 'ml'.

public UnitConverter(String unit)
{
if (unit.equals("oz"))
{
factor = oz_TO_ml;
} else if (unit.equals("gal"))
{
factor = gal_TO_g;
} else if (unit.equals("lb"))
{ factor = lb_TO_kg;
}
}
If you pass "ml" the factor will be zero
Your design currently needs two of these but you really only need one as "oz" has everything it needs to do the conversion.
Ignore the the toUnit in your line input code and just use fromUnit
Edit : I'll show you an alternative way to do things, it just supports one convert to show the rough design. Note the method calls are now static because you will only ever need one instance of them
UnitConverter.java
public class UnitConverter
{
private static final double oz_TO_ml = 29.5735;
public static double convert(String fromType, String toType,double amount) throws IllegalArgumentException
{
if (fromType.equals("oz") && toType.equals("ml"))
{
return (amount * oz_TO_ml);
}
else
{
throw new IllegalArgumentException("The combination of converting " + fromType + " to " + toType + " is not supported");
}
}
}
Calculator.java:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
System.out.print("Value ");
double val = in.nextDouble();
System.out.println(val + " " + fromUnit + " = " + UnitConverter.convert(fromUnit,toUnit,val) + " " + toUnit);
}
}

Your UnitConverter class constructor only knows about 3 units: oz, gal, and lb. If you instantiate it with one of those, it will correctly assign the factor and be able to convert units, as seen below:
public UnitConverter(String unit) {
if (unit.equals("oz")) {
factor = oz_TO_ml;
} else if (unit.equals("gal")) {
factor = gal_TO_g;
} else if (unit.equals("lb")) {
factor = lb_TO_kg;
}
}
However, in your Calculator class, you have this line:
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
If you run your program with your sample input, from is oz and to is ml. But if you instantiate UnitConverter with the unit ml, what does factor get set to? According to your constructor, it is never set, and so it retains its default value of 0.0.
Later, you call this line:
double converted = to.fromOz(oz);
This runs the fromOz method
public double fromOz(double amount) {
return (amount / factor);
}
Which divides by the factor, which is 0.0. This is the source of your Infinity output.
As the other answer says, you don't need to have two UnitConverter objects to perform this calculation. The factor is correct to convert between ounces and millilitres, so this Calculator code is sufficient.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
System.out.print("Value ");
double val = in.nextDouble();
double result = from.toMl(val);
System.out.println(val + " " + fromUnit + " = " + result + " ml.");
}
}
If you wanted to keep your current calculator code, you would need to add a condition in your UnitConverter constructor for a scalefactor for ml (1.0). However, I think this approach is flawed because what happens, for example, when you try to convert between oz and inches? The conversion makes no sense but your architecture would not prevent it.

Related

Why does my program crash when I display the percentage symbol?

This program compiles and runs perfectly if I remove '%%' from the 'toString()' method. However, if I display the percentage symbol, my program crashes right when the 'toString()' method is called (after asking for input). I failed to resolve this issue. Can anybody help me?
I am running this on VSCODE.
// FA2022_Investor_Souza.java
// Data type class
public class FA2022_Investor_Souza {
// Fields
private String name;
private int shareAmount;
private float sharePrice;
private float yearlyDividend;
// No-arg constructor
public FA2022_Investor_Souza()
{
name = "";
shareAmount = 0;
sharePrice = 0f;
yearlyDividend = 0f;
}
// Parameterized constructor
public FA2022_Investor_Souza(String n, int a, float p, float y)
{
name = n;
shareAmount = a;
sharePrice = p;
yearlyDividend = y;
}
// Method to calculate the savings money
public float savingsMoney()
{
float moneyInvested = sharePrice * shareAmount;
float interestAmount = moneyInvested * yearlyDividend * 0.01f;
float moneyReturned = moneyInvested + interestAmount;
return moneyReturned;
}
// Method to display the information
public String toString ()
{
float moneyInvested = sharePrice * shareAmount;
float interestAmount = moneyInvested * yearlyDividend * 0.01f;
return "-------------------------------------------------------\n" +
"FA2022_ShareInvestmentCalculator_Souza.java\n" +
"FALL 2022 semester - MATHEUS SOUZA\n" +
"-------------------------------------------------------\n" +
String.format("%-32.32s%15s\n", "Name of investor: ", name) +
String.format("%-32.32s%15d\n", "Number of shares: ", shareAmount) +
String.format("%-32.32s%15.2f\n", "Price of each share: ", sharePrice) +
String.format("%-32.32s%15.2f%%\n", "Percentage of yearly dividend: ", yearlyDividend) +
String.format("%-32.32s%15.2f\n", "Money Invested: ", moneyInvested) +
String.format("%-32.32s%15.2f\n", "Interest Amount: ", interestAmount) +
"-------------------------------------------------------\n" +
String.format("%-32.32s%15.2f\n", "Total money at the end of year: ", savingsMoney());
}
}
// FA2022_ShareInvestmentCalculator_Souza.java
// Driver class
// Importing Scanner class
import java.util.Scanner;
public class FA2022_ShareInvestmentCalculator_Souza {
public static void main (String [] args)
{
// Creating object for Scanner class
Scanner scanner = new Scanner(System.in);
// Asking for the user's info
System.out.printf("What is your name? ");
String name = scanner.nextLine();
System.out.printf("What is the number of shares? ");
int number = scanner.nextInt();
System.out.printf("What is the price of a share? ");
float price = scanner.nextFloat();
System.out.printf("What is the yearly dividend? ");
float dividend = scanner.nextFloat();
// Creating object for FA2022_Investor_Souza class using parameterized constructor
FA2022_Investor_Souza investor = new FA2022_Investor_Souza(name, number, price, dividend);
// Displaying the result by accessing the method toString()
System.out.printf(investor.toString());
}
}
Relating to this line of your code
String.format("%-32.32s%15.2f%%\n", "Percentage of yearly dividend: ", yearlyDividend)
You want to add another % as a string after the yearlyDividend, correct?
Then you need to tell in the format string that another string is following (%s). Then add the "%%" as string as another parameter, because %'s need to be escaped by another % to be shown as the % sign.
So the working code would look like this:
String.format("%-32.32s%15.2f%s\n", "Percentage of yearly dividend: ", yearlyDividend, "%%")

Returning a value from one method to another to be used in the output

I can't figure out how to return the value of finalCost to the main method and have it printed.
import java.util.*;
public class PhonePlan {
private static double basecost = 8.5;
private static double rate = 0.35;
private static double discount = 0.15;
public static void main(String[] args) {
//Scan input for downloadLimit
Scanner scan = new Scanner(System.in);
System.out.print("Enter the download limit in GB: ");
int downloadLimit = scan.nextInt();
// Call other method
calcMonthlyCharge(downloadLimit);
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost));
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
}
Specifically, I can't find how to use the returned value in the "println" line.
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
You call calcMonthlyCharge(downloadLimit),but don't store the returnvalue.
When you call System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
It is unknown what finalcost is, this is a variable which only exist in the scope of calcMonthlyCharge
Either store the returnvalue of calcMonthlyCharge(downloadLimit) and reuse the value to print, or use calcMonthlyCharge(downloadLimit) in your println with downloadLimit as parameter to get a new returnvalue.

Simulating a gas station

So I'm supposed to create a program where I have a gas station with 5 gas pumps and and I don't know how to keep track of the statistics, the program correctly subtracts the amount of gas left from the type of gas tank but when the next customer pumps gas the statistics get erased? any help would be appreciated, here is my code. keep in my mind this is part of a 5 class program and this is only one part.
import java.util.Random;
import java.util.Scanner;
public class GasPump
{
static Scanner Input = new Scanner (System.in);
private static double totalRevenue;
private static double currentPurchase;
//private int currentGasType;
private static double currentGasType;
private static double currentGasAmount;
private Client currentClient;
private int clock;
private static double regularTank;
private static double plusTank;
private static double supremeTank;
//private static double amountLeftInTank;
public void updatePump()
{
if (currentClient != null)
{
clock--;
if (clock == 0)
{
//totalRevenue += currentPurchase;
totalRevenue = totalRevenue + currentPurchase;
resetPump ( );
}
}
}
public void resetPump ( )
{
clock = 0;
currentClient = null;
currentPurchase = 0;
//currentGasType = "";
currentGasType = 0;
currentGasAmount = 0;
}
public boolean pumpOpen()
{
return (clock == 0) && (currentClient == null);
}
public static double getCurrentGasType()
{
regularTank = 1000;
plusTank = 1000;
supremeTank = 1000;
//Scanner Input = new Scanner(System.in);
System.out.println("What type of gas would you like?");
System.out.println("Regular , Plus or Premium");
System.out.println("1)Regular: $2.99 per gallon; 2)Plus: $3.99 per gallon; 3)Premium: $4.99 per gallon");
currentGasType = Input.nextDouble();
Random gen = new Random ();
//currentGasAmount = gen.nextDouble ()* 45;
currentGasAmount = gen.nextDouble()*50;
double roundOff = (double) Math.round(currentGasAmount * 100) / 100;
//System.out.println("How many gallons would you like?");
//currentGasAmount = Input.nextDouble();
if (currentGasType == 1)
{
currentGasType = 2.99;
regularTank = regularTank - currentGasAmount;
}
else if (currentGasType == 2)
{
currentGasType = 3.99;
plusTank = plusTank - currentGasAmount;
}
else
{
currentGasType = 4.99;
supremeTank = supremeTank - currentGasAmount;
}
System.out.println("# of gallons purchased: " + currentGasAmount);
System.out.println("Amount of regular gas left: " + regularTank);
System.out.println("Amount of plus gas left: " + plusTank);
System.out.println("Amount of supreme gas left: " + supremeTank);
return currentGasType;
}
/*public static double getCurrentGasAmount() {
Random gen = new Random ();
currentGasAmount = gen.nextDouble ()* 50;
//System.out.println("How many gallons would you like?");
//currentGasAmount = Input.nextDouble();
System.out.println("# of gallons purchased: " + currentGasAmount);
return currentGasAmount;
}
*/
public static double getCurrentPurchase()
{
currentPurchase = currentGasType * currentGasAmount;
return currentPurchase;
}
public static double getTotalRevenue() {
totalRevenue += currentPurchase;
System.out.println("Total revenue so far is " + totalRevenue);
return totalRevenue;
}
/*public static double getAmountLeftInTank()
{
regularTank = 1000;
plusTank = 1000;
supremeTank = 1000;
if (currentGasAmount == 1)
if (currentGasType == 1)
{
//regularTank = regularTank - currentGasAmount;
}
else if (currentGasType == 2)
else if (currentGasAmount == 2)
{
//plusTank = plusTank - currentGasAmount;
}
else
{
supremeTank = supremeTank - currentGasAmount;
}
System.out.println("Amount of regular gas left: " + regularTank);
System.out.println("Amount of plus gas left: " + plusTank);
System.out.println("Amount of supreme gas left: " + supremeTank);
return amountLeftInTank;
}
*/
public void serveAClient (Client aClient)
{
clock = 10;
currentClient = aClient;
GasPump.getCurrentGasType();
System.out.println("Your total is " + GasPump.getCurrentPurchase());
GasPump.getTotalRevenue();
//GasPump.getAmountLeftInTank();
/*
* design get methods
* ask client what type of gas he wants
* add more code here
*/
// add the total here
}
}
Don't use static fields for the data stored in GasPump.
static fields are singletons, they only have a single value shared across all instances of GasPump. This means that if you have multiple instances of GasPump, then calling reset will reset all of the gas pumps.
By removing the keyword static from each of the fields, then there will be a separate copy of the field held for each of the GasPump's. And thus calling reset will only wipe the fields for that one instance of GasPump.
The following diagram may help you to visualise the difference:
In this example, count has been shared across instances c1 and c2 of CircleWithCount.
You can read more detail about using the static keyword on fields here: What does the 'static' keyword do in a class?

Trouble Calling and Using Java Methods

I just started learning Java and I'm trying to write a program based on an assignment sheet (gave this sheet at bottom of the post). However, I really don't quite understand how to use methods all that well. I've written my methods in the "Customer.java" class, and I'm trying to use them in my "TestCustomer.java" class. However, since I really don't know how to do this, it has turned out horribly. I've searched for information on this, but I just seem to keep making myself more confused. Is there any chance you guys could show me the correct way to use these methods, or at least point me in the right direction? Thank you a ton for any help you can provide.
Customer class
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Customer {
public static double taxRate = 0.00;
public static double saleRate = 0.00;
String customerName;
double listSaleAmount;
double saleDiscount = 0;
double netSaleAmount;
double taxAmount;
double saleTotal;
boolean taxable;
public Customer (String CustomerName, boolean taxable) {
}
public double calculateTax (double listSaleAmount) {
saleDiscount = listSaleAmount*saleRate;
netSaleAmount = listSaleAmount-saleDiscount;
if (taxable == true) {
taxAmount = netSaleAmount*taxRate;
}
else {
taxAmount = 0.00;
}
saleTotal = listSaleAmount + taxAmount;
return saleTotal;
}
public String printRecord; {
System.out.println("Customer is " + customerName);
System.out.println("Sale amount is $" + listSaleAmount);
System.out.println("Discount amount is $" + saleDiscount);
System.out.println("Net Sale Amount is $" + netSaleAmount);
System.out.println("Tax amount is $" + taxAmount);
System.out.println("Total Sale Amount is $" + saleTotal);
}
public static double changeTaxAmount (double taxRate) {
Scanner input = new Scanner(System.in);
double userTaxAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Tax Rate? (8.25 & 8.50 for testing)"));
taxRate = userTaxAmount;
return taxRate;
}
public static double changeSaleRate (double saleRate) {
Scanner input = new Scanner(System.in);
double userSaleAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Sale Discount Rate? (0.00 & 7.50 for testing)"));
saleRate= userSaleAmount;
return saleRate;
}
public static String printTaxRate; {
System.out.println("Tax Rate is" + taxRate + "%.");
}
public static String printSaleRate; {
System.out.println("The Sale Rate is" + saleRate + ".");
}
}
TestCustomer class
import java.math.BigDecimal;
public class TestCustomer {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer customer1 = new Customer("Annie Smith", true);
Customer customer2 = new Customer("Bob Wilson", false);
Double totalOfAllSales = 0.00;
//I have no clue how to actually use the methods I created in the Customer class!
//These are my best guesses, which are obviously wrong
//Any help here would be greatly appreciated!
Customer.changeTaxAmount(taxRate);
Customer.printTaxRate;
Customer.changeSaleRate(saleRate);
Customer.printSaleRate;
customer1.listSaleAmount = 65.00;
customer2.listSaleAmount = 52.00;
totalOfAllSales += customer1.calculateTax;
totalOfAllSales += customer2.calculateTax;
customer1.printRecord;
customer2.printRecord;
Customer.changeTaxAmount(taxRate);
Customer.printTaxRate;
Customer.changeSaleRate(saleRate);
Customer.printSaleRate;
customer1.listSaleAmount = 84.00;
customer2.listSaleAmount = 105.00;
totalOfAllSales += customer1.calculateTax;
totalOfAllSales += customer2.calculateTax;
customer1.printRecord;
customer2.printRecord;
System.out.println("The total of all sales is $" + totalOfAllSales);
}
}
Assignment sheet (Not worrying about printing to a file right now, just want the main mechanics to work)
You seem to be confused about the syntax for calling a method. The syntax is as follows:
object.method(arguments)
If there are no arguments it looks like this:
object.method()
Also, you need to use accessor and mutator methods instead of directly setting instance variables like you do here:
customer1.listSaleAmount = 65.00;
You should implement methods like these:
public void setListSaleAmount(double lsa) {
listSaleAmout = lsa;
}
public double getListSaleAmount() {
return listSaleAmount;
}
and make listSaleAmount private.
Problem #2: The syntax for defining the methods. You are using this code to define a method:
public static String printTaxRate; {
System.out.println("Tax Rate is" + taxRate + "%.");
}
You should be using this code:
public static String printTaxRate() {
System.out.println("Tax Rate is" + taxRate + "%.");
}
The problem is the weirdly placed semicolon inside the method header.

Java my loan class formula is returning infinity

I have my code running perfectly, except for my return value for the monthly loan calculator. It keeps on returning Infinity for both my monthly payments and total payments. Please help with the formula. This is a homework. All i need to know is if I am implementing the formula incorrectly. I get the feeling that it is somehow trying to divide over 0 and then returning infinity, but I could be wrong.
public class MyLoan
{
private double amountBorrowed;
private double yearlyRate;
private int years;
public double A;
public double n = years * 12;
public MyLoan(double amt, double rt, int yrs)
{
amountBorrowed = amt;
yearlyRate = rt;
years = yrs;
}
public double getAmountBorrowed()
{
return amountBorrowed;
}
public double getYearlyRate()
{
return yearlyRate;
}
public int getYears()
{
return years;
}
public double monthlyPayment()
{
double i = (yearlyRate / 100) / 12;
A = (amountBorrowed) * (i * Math.pow(1+i, n)) / (Math.pow(1+i, n) -1);
return A;
}
public double totalPayment()
{
return A * (years * 12);
}
public String toString()
{
return "Loan: " + "$" + amountBorrowed + " at " + yearlyRate + " for " + years + " years";
}
public static void main(String[] args)
{
final double RATE15 = 5.75;
final double RATE30 = 6.25;
StdOut.println("***** Welcome to the Loan analyzer! *****");
String ans = "Y";
do {
StdOut.print("\n Enter the principle amount to borrow: ");
double amount = StdIn.readDouble();
MyLoan fifteenYears = new MyLoan(amount, RATE15, 15);
MyLoan thirtyYears = new MyLoan(amount, RATE30, 30);
double amount15 = fifteenYears.monthlyPayment();
double total15 = fifteenYears.totalPayment();
double amount30 = thirtyYears.monthlyPayment();
double total30 = thirtyYears.totalPayment();
StdOut.println("===========ANALYSES==========");
StdOut.println(fifteenYears);
StdOut.println("Monthly payment = " + "$" + amount15);
StdOut.println("Total payment = " + "$" + total15);
StdOut.println("");
StdOut.println("");
StdOut.println(thirtyYears);
StdOut.println("Monthly payment = " + "$" + amount30);
StdOut.println("Total payment = " + "$" + total30);
StdOut.println("=============================");
StdOut.print("\n ** Do you want to continue (y/n)? ");
ans = StdIn.readString();
} while (ans.toUpperCase().equals("Y"));
StdOut.println("\n********** Thank you. Come again! **********");
}
}
You should be debugging this yourself, but I'll give you a hint. What is 1^n (where n is a positive integer)? Where, in your code, are you using this construct?
There is many ways to calculate interest and the most common is just
A = amountBorrowed * (yearlyRate / 100) / 12;

Categories