How to create an AddCoins application? - java

that prompts the user for the number of pennies, nickels, dimes, and quarters, and then displays their total dollar amount. The application should include a getDollarAmount() method that has 4 int parameters corresponding to the number of pennies, nickels, dimes, and quarters and returns a String that corresponds to the dollar value of the coins.
the application output should look similar to:
Enter you total coins:
Quarters:3
Dimes:2
Nickels:1
Pennies:8
Total: $1.08
and this is my attempt:
package ch7e5;
import java.util.Scanner;
public class Ch7E5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n1, p, d, n, t;
double Q1, D1, N1, P1;
System.out.println("Enter your total coins:");
System.out.print("Quarters:");
n1 = input.nextInt();
System.out.print("Dimes:");
d = input.nextInt();
System.out.print("Nickles:");
n = input.nextInt();
System.out.print("Pennies:");
p = input.nextInt();
double Q1 = (pennies * 0.01);
private static double calctotal(double Q1, double D1, double P1, double N1) {
double dbltotal;
dbltotal = (Q1 + D1 + P1 + N1);
return dbltotal;
}
}
This is my 2nd attempt with the help of your comments:
package chapter7ex5;
import java.util.Scanner;
public class Chapter7ex5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your total coins:");
System.out.print("Quarters:");
int Q1 = input.nextInt();
System.out.print("Dimes:");
int D1 = input.nextInt();
System.out.print("Nickles:");
int N1 = input.nextInt();
System.out.print("Pennies:");
int P1 = input.nextInt();
}
public static double calctotal(int Q1, int D1, int N1, int P1) {
double total;
total=((0.25 * Q1) + (0.1 * D1) + (0.05 * N1) + (0.01 * P1));
return (total);
}}
I think my attempts are over:
package chapter7ex5;
import java.text.DecimalFormat;
import java.util.Scanner;
public class Chapter7ex5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your total coins:");
System.out.print("Quarters:");
int Q1 = input.nextInt();
System.out.print("Dimes:");
int D1 = input.nextInt();
System.out.print("Nickles:");
int N1 = input.nextInt();
System.out.print("Pennies:");
int P1 = input.nextInt();
DecimalFormat fmt = new DecimalFormat("$#,###.##");
System.out.println("Total:"+fmt.format(calctotal(Q1, D1, N1,
P1)));
}
public static double calctotal(int Q1, int D1, int N1, int P1) {
double total;
total=((0.25 * Q1) + (0.1 * D1) + (0.05 * N1) + (0.01 * P1));
return (total);
}}

Well, one quarter is usually worth 0.25. A dime is worth ten cents and so on. Also, you seem to have swapped nickels and pennies. And your numbers will always be int. Finally, a method does not go within the body of another method. So, move calctotal outside of main() and calculate the values of your coins with something like
private static double calctotal(int Q1, int D1, int N1, int P1) {
return ((0.25 * Q1) + (0.1 * D1) + (0.05 * N1) + (0.01 * P1));
}
You should probably call flush() if you use System.out.print(), it isn't automatic without a newline. Then you could use a DecimalFormat to format your calculate total like
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your total coins:");
System.out.print("Quarters:");
System.out.flush();
int quarters = input.nextInt();
System.out.print("Dimes:");
System.out.flush();
int dimes = input.nextInt();
System.out.print("Nickles:");
System.out.flush();
int nickels = input.nextInt();
System.out.print("Pennies:");
System.out.flush();
int pennies = input.nextInt();
DecimalFormat fmt = new DecimalFormat("$#,###.##");
System.out.println(fmt.format(calctotal(quarters, dimes, nickels,
pennies)));
}

Not bad. Something I noticed is that you only calculate the double value of the pennies, not the quarters, dimes, and nickels. That conversion should also be done inside your function:
private static double calcTotal(int pennies, int nickels, int dimes, int quarters)
{
return ((pennies * 0.01) + (nickels * 0.05) + (dimes * 0.10) + (quarters * 0.25));
}
Outputting the amount is easy too, just use something like this in your main function:
System.out.printf("%.2f",calcTotal(p, n, d, q));
The doubles have have created in your main aren't necessary, and you should change how you get your amounts of coins to:
System.out.print("Quarters: ");
q = Integer.parseInt(input.nextLine());

Related

How to do an array in a loop

I am making an investment calculator.
So I will be doing a math problem and I want to loop it through each array and there will be 12 of them.
So let's say I am going to invest $1000 with a rate return of 4.5%.
So I will need to do 1000 * 0.045 + 1000 = 1,045 that equals one month. Then I need to do 1,045 * 0.045 + 1,045 = 1,092 that would equal the second month and how would I have it go through a loop like that?
Would I use a for loop? or?
This is what I have so far maybe you'll get it better by reading it. But I still need to create a loop that would like the example I gave above.
public class SimpleInvestment {
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
double [] num = new double [11];
printWelcome();
double investTotal = getInvestAmount();
double rateTotal = getRate();
}
public static void printWelcome()
{
System.out.println("Welcome to the Investment Calulator");
}
public static double getInvestAmount()
{
double amountInvest;
System.out.print("Hou much will you be investing? ");
amountInvest = input.nextDouble();
while (amountInvest <= 0)
{
System.out.println("Amount must be greater than 0. Try again.");
System.out.print("How much will you be investing? ");
amountInvest = input.nextDouble();
}
return amountInvest;
}
public static double getRate()
{
double rate;
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
while (rate < 0 )
{
System.out.println("Rate must be greater than 0. Try again.");
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
}
return rate;
}
public static void calculateInterst( double num[], double investTotal, double rateTotal)
{
double total;
rateTotal = rateTotal / 100;
total = investTotal * rateTotal + investTotal;
}
}
You can use a while or for loop. In this example I used a for loop.
There is documentation in the code to walk you through the logic.
public static void calculateInterest(double num, double investTotal, double rateTotal) {
double total; //keep the total outside loop
rateTotal = rateTotal / 100; //your percent to decimal calculation
total = investTotal * rateTotal + investTotal; //intial calculation
for (int i = 1; i < num; i++) {//for loop starting at 1 because we alreay calculated the first
total += (total * rateTotal);//just calculate the rate of change
}
System.out.println(total);//either output it or return it. Whatever you want to do from here.
}
I hope this helps!
You can use below code:
where months is the investment duration in months,
investment is the amount that is being invested,
rate is the interest rate. e.g. 0.045
public static double calculateTotal(int months, double investment, double rate) {
double total = investment;
for (int i=1; i <= months; i++) {
total = total + (total * rate);
}
return total;
}

How to get results from another method into another method using java?

I made a simple grade system for fun. I'm trying to apply the total of grades and add it to an equation in my getApercent() method. However, I keep getting errors and don't know what to do.
package gradesystem;
import java.util.Scanner;
public class Gradesystem {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Gradesystem gs = new Gradesystem();
// TODO Auto-generated method stub
int Acount,Bcount,Ccount,Dcount,Fcount;
double ap,bp,cp,dp,fp;
System.out.println("Enter the amount of A's");
Acount = keyboard.nextInt();
System.out.println("Enter the amount of B's");
Bcount = keyboard.nextInt();
System.out.println("Enter the amount of C's");
Ccount = keyboard.nextInt();
System.out.println("Enter the amount of D's");
Dcount = keyboard.nextInt();
System.out.println("Enter the amount of F's");
Fcount = keyboard.nextInt();
int grades;
ap = getApercent(Acount);
System.out.println(ap);
bp = getBpercent(Bcount);
System.out.println(bp);
cp = getCpercent(Ccount);
System.out.println(cp);
dp = getDpercent(Dcount);
System.out.println(dp);
fp = getFpercent(Fcount);
System.out.println(fp);
}
public static void Totalgrades(int acount, int bcount, int ccount, int dcount, int fcount){
int totalofgrades = acount + bcount + ccount + dcount + fcount;
System.out.print(totalofgrades);
}
public static double getApercent(int a){
double ap;
ap = (a/a * 100) + 0.5;
return Math.round(ap);
}
public static double getBpercent(int b){
double bp;
bp = (b/b * 100) + 0.5;
return Math.round(bp);
}
public static double getCpercent(int c){
double cp;
cp = (c/c * 100) + 0.5;
return Math.round(cp);
}
public static double getDpercent(int d){
double dp;
dp = (d/d * 100) + 0.5;
return dp;
}
public static double getFpercent(int f){
double fp;
fp = (f/f * 100) + 0.5;
return fp;
}
}
A little bit of guessing here. But the methods that calculate the percentage seem off. Again, assuming; but to calculate the percentage of a whole you would use the following formula percentage = part/whole * 100
e.g.
we have 9 grades and 3 are A's, 3 are B's, 2 are C's, 1 is D's, and 0 are E's.
Then I'd expect the percentages to be as follows:
33% A // 3 / 9 * 100
33% B // 3 / 9 * 100
22% C // 2 / 9 * 100
11% D // 1 / 9 * 100
0% E // 0 / 9 * 100
One other thing to point out is the the operator / with two ints does integer division. So 3 / 9 == 0.
You could replace all the specific methods with a more generic version.
public static double getPercentage(int gradeCount, int totalNumberOfGrades) {
double percentage = ( gradeCount / (double) totalNumberOfGrades * 100);
return Math.round(percentage);
}

Java Invoking Methods and returning data

I am brand new to Java… I have an assignment that is discussing Methods. For some reason when I invoke my methods and pass the data back to my main everything is "-Infinity" or "0". I have been trying to resolve this for two days straight and I can't seem to find an appropriate solution.
I'm only including the code for the first portion of the assignment because I have a feeling that whatever mistake I am making… I'm making it throughout the entire assignment. So if someone could assist me with this portion it would allow me to hopefully correct my other issues too.
The first method returns: -Infinity, but when I take the code apart and run it without the use of methods… I get 11.8, which is correct.
Any assistance would be greatly appreciated!
/*
* Anthony Vincenzo Laginess
* CIT 130
* Oct. 12th, 2016
* HMW 07 - Methods
* Time Needed:
*/
package cit130hmw07_laginess;
import java.util.Scanner;
public class CIT130HMW07_Laginess {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//*************************************************
//****************** Method 1 *********************
//*************************************************
//This method calculates body fat. It takes your gender as a parameter
//and outputs your bodyfat.
System.out.println("Please enter your gender...");
String gender = input.nextLine();
System.out.println("Please enter your weight: ");
int bodyWeight = input.nextInt();
System.out.println("Please enter your waist measurement: ");
int waistSize = input.nextInt();
if(gender.equalsIgnoreCase("male")) {
bodyFatMale(bodyWeight, waistSize);
double bodyFatPercentage = bodyFatMale(bodyWeight, waistSize);
System.out.println("Your body fat is: " + bodyFatPercentage); }
else if(gender.equalsIgnoreCase("female")) {
System.out.println("Please enter your waist size: ");
int waist = input.nextInt();
System.out.println("Please enter your hip size: ");
int hips = input.nextInt();
System.out.println("Please enter your forearm size: ");
int forearms = input.nextInt();
bodyFatFemale(bodyWeight, waistSize, waist, hips, forearms);
double answer = bodyFatFemale(bodyWeight, waistSize, waist, hips,
forearms);
System.out.println("Your body fat is: " + answer); }
else
//enter an error message
}//main
//METHOD 1: Bodyfat calculations
public static double bodyFatMale(int bodyWeight, int waistSize) {
int weight = 0;
int waist = 0;
double A1;
double A2;
double B;
double actualBodyFat;
double bodyFatPercentage;
A1 = (weight * 1.082) + 94.42;
A2 = waist * 4.15;
B = A1 - A2;
actualBodyFat = weight - B;
bodyFatPercentage = actualBodyFat * 100 / weight;
return bodyFatPercentage; }
public static double bodyFatFemale(int bodyWeight, double wristSize, double waistSize, double hipSize, double forearmSize) {
int weight = 0;
double wrist = 0;
double waist = 0;
double hips = 0;
double forearms = 0;
double A1, A2, A3, A4, A5, B;
double actualBodyFat;
double bodyFatPercentage;
A1 = (weight * .732) + 8.987;
A2 = wrist / 3.14;
A3 = waist * 0.157;
A4 = hips * 0.249;
A5 = forearms * 0.434;
B = A1 + A2 - A3 - A4 + A5;
actualBodyFat = weight - B;
bodyFatPercentage = actualBodyFat * 100 / weight;
return bodyFatPercentage; }
}//class
In each of your methods, you are setting all of your variables equal to 0, so the calculations inside the methods are being performed with 0s. Instead, you need to assign the variables to the values that you're passing in as parameters.
So instead of
int weight = 0;
try
int weight = bodyWeight;
Hint: In the bodyFat methods, you have two variables for the body Weight and waist size. And you are using the wrong one; i.e. the one that you have initialized to ero. You should only have one.
You are not actually using your method parameters in your calculations.
Here would be the fixed version of your first method:
//METHOD 1: Bodyfat calculations
public static double bodyFatMale(int bodyWeight, int waistSize) {
double A1;
double A2;
double B;
double actualBodyFat;
double bodyFatPercentage;
A1 = (bodyWeight* 1.082) + 94.42;
A2 = waistSize* 4.15;
B = A1 - A2;
actualBodyFat = bodyWeight- B;
bodyFatPercentage = actualBodyFat * 100 / bodyWeight;
return bodyFatPercentage;
}
public static double bodyFatMale(int bodyWeight, int waistSize) {
int weight = 0; // Introducing `0` into all calculations
.....
A1 = (weight * 1.082) + 94.42; // Should be `bodyWeight`?
A2 = waist * 4.15; // Should be `bodyWeight`?
B = A1 - A2;
actualBodyFat = weight - B; // Should be `bodyWeight`?
bodyFatPercentage = actualBodyFat * 100 / weight; // Should be `bodyWeight`?

Issue with compare two fractions

I have two classes: Fraction and Test. I already do well with class Fraction, but class Test has some issues.
I want to allow the user enter the fractions and store in ArrayList, the user can compare two fraction from the array by choosing the index of the array. But when I compare two fraction, it doesn't work well!
class Fraction:
class Fraction {
private int numerator;
private int denominator;
Fraction(int n, int d) {
numerator = n;
denominator = d;
}
public Fraction(int n) {
this(n, 1);
}
public Fraction() {
numerator = 0;
denominator = 1;
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int denominator) {
this.denominator = denominator;
}
public void display() {
String s = this.getNumerator() + "/" + this.getDenominator();
System.out.println(s);
}
public double evaluate() {
double n = numerator;
double d = denominator;
return (n / d);
}
public boolean isEquals(Fraction f){
int gcd1 = gcd(f.getNumerator(), f.getDenominator());
double fractionFloatValue = (f.getNumerator()/gcd1) / (f.getDenominator()/gcd1);
int gcd2 = gcd(this.getNumerator(), this.getDenominator());
double fractionFloatValue2 = (this.getNumerator()/gcd2) / (this.getDenominator()/gcd2);
return (fractionFloatValue == fractionFloatValue2) ? true : false;
}
public Fraction add(Fraction f2) {
Fraction r = new Fraction((numerator * f2.denominator)
+ (f2.numerator * denominator), (denominator * f2.denominator));
return r;
}
static private int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
public static String asFraction(int x, int y) {
int gcd = gcd(x, y);
return (x / gcd) + "/" + (y / gcd);
}
/*public static void main(String[] argv) {
Fraction f0 = new Fraction();
Fraction f1 = new Fraction(3);
Fraction f2 = new Fraction(20, 60);
Fraction f3 = new Fraction(1, 3);
System.out.println("--------------Testing constructors--------------");
f0.display();
f1.display();
f2.display();
System.out.println("--------------Test if two fractions is equal--------------");
System.out.println(f2.isEquals(f1));
}*/
}
and class Test:
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void enterFraction(){
ArrayList<Fraction> arr = new ArrayList<Fraction>();
Scanner scanner = new Scanner(System.in);
boolean check = false;
int i = 1;
while(!check){
System.out.println("Enter fraction"+i+":");
Fraction f = new Fraction();
System.out.println("Enter Numerator: ");
int numerator = scanner.nextInt();
scanner.nextLine();
f.setNumerator(numerator);
System.out.println("Enter Denominator: ");
int denominator = scanner.nextInt();
scanner.nextLine();
f.setDenominator(denominator);
System.out.println("Your fraction"+i+" is: "+f.getNumerator()+"/"+f.getDenominator());
arr.add(f);
System.out.println("Want to compare fractions? (Y/Yes or N/No)");
String compareRequest = scanner.nextLine();
if(compareRequest.equalsIgnoreCase("y")){
System.out.println("Choose your target fraction!!! (enter the index of the array)");
int position = scanner.nextInt();
scanner.nextLine();
Fraction targetFraction = arr.get(position);
targetFraction.display();
System.out.println("Choose your second fraction to compare!!! (enter the index of the array)");
int position2 = scanner.nextInt();
scanner.nextLine();
Fraction secondFraction = arr.get(position2);
secondFraction.display();
boolean compareTwoFractions = secondFraction.isEquals(targetFraction);
if(compareTwoFractions == true){
System.out.println("Two fractions are equal");
}
else if(compareTwoFractions == false){
System.out.println("Two fractions are not equal");
}
}
i++;
System.out.println("Do you want to enter more fraction? (Y/Yes or N/No)");
String checkRequest = scanner.nextLine();
if(checkRequest.equalsIgnoreCase("n")){
check = true;
}
}
}
public static void main(String[] args){
enterFraction();
}
}
I input like this:
Enter fraction1:
Enter Numerator:
2
Enter Denominator:
4
Your fraction1 is: 2/4
Want to compare fractions? (Y/Yes or N/No)
n
Do you want to enter more fraction? (Y/Yes or N/No)
y
Enter fraction2:
Enter Numerator:
1
Enter Denominator:
3
Your fraction2 is: 1/3
Want to compare fractions? (Y/Yes or N/No)
y
Choose your target fraction!!! (enter the index of the array)
0
2/4
Choose your second fraction to compare!!! (enter the index of the array)
1
1/3
Two fractions are equal
Do you want to enter more fraction? (Y/Yes or N/No)
You see it not work, 2/4 == 1/3. Please point me somethings with this.
The problem is that getNumerator(), getDenominator(), and gcd return an int. Therefore, the division inside your equals method is done in integers:
double fractionFloatValue = (f.getNumerator()/gcd1) / (f.getDenominator()/gcd1);
...
double fractionFloatValue2 = (this.getNumerator()/gcd2) / (this.getDenominator()/gcd2);
The value of fractionFloatValue and fractionFloatValue2 are, in fact, integers, even though they are assigned to variables of type double. Both 1/3 and 1/2 are proper fractions, so integer division evaluates to zero in both cases. That's why your equals returns true in both cases.
There are two ways to fix this:
Declare gcd1 and gcd2 as double. This would force the division into double; unfortunately, your code would suffer from double comparison for equality, which is inherently imprecise, or
Use identity n1/d1 == n2/d2 when n1*d2 == n2*d1. This eliminates division, so you get perfect precision in your comparisons until you overflow (and you would not overflow with the constraints that you are using if you use long for the results of your multiplication).
I change two line that #dasblinkenlight has mentioned by:
double fractionFloatValue = ((f.getNumerator()/gcd1)*1.0) / (f.getDenominator()/gcd1);
double fractionFloatValue2 = ((this.getNumerator()/gcd2)*1.0) / (this.getDenominator()/gcd2);
and It worked now.

Dividing values from one array by values from a separate array

I am trying to take values from separate arrays and perform divisional math. I have created a method to perform the division, but I keep getting the "bad operand..." error. I have searched and searched, but cannot find resolution. I need to be able to take the values from tripMiles and divide that by the values from gallons.
import java.util.Scanner;
public class Week6Challenge {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int count = 0;
//double miles = 0, gallons = 0;
//Arrays
String[] tripName;
tripName = new String[11];
double[] tripMiles;
tripMiles = new double[11];
double[] tripMPG;
tripMPG = new double [11];
double[] gallons;
gallons = new double [11];
//double miles = 0, gallons = 0;
while (count <= 9){//start while
System.out.println("Enter a description of this trip");
tripName[count] = scan.next();
System.out.println("How many miles did you drive?");
tripMiles[count] = scan.nextDouble();
System.out.println("How many gallons of gas did you use on this trip");
gallons[count] = scan.nextDouble();
count++;
}//end while
tripMPG[count] = answer(tripMiles, gallons);
System.out.println("Trip Name \t Miles Traveled \t MPG");
int k = 0;
for(k = 0; k < 10; k++){
System.out.println(tripName[k]+ "\t\t" + tripMiles[k] + "\t\t\t" + tripMPG[k]);
}
}
public static double answer(double[] num1, double[] num2){
return (num1/num2);
}
}
You are trying to divide two arrays like:
return (num1/num2);
Which is not valid.
Instead if you need length or sum of two arrays and then divide, you could sum up all the elements and then divide the two values.
You can't divide array like this (num1/num2)
Code snippet of one method how to do division of arraya
public static double answer(double[] num1, double[] num2){
//assumimg both array is of equal length
for (int i=0;i<num1.length;i++){
double result = num1[i]/num2[i];
}
}
As already been mentioned you can't divide arrays to each other, but their elements.
Change your answer function so instead of two arrays of double it takes two double and returns the result:
//num1 & num2 are double, not array
public static double answer(double num1, double num2){
return (num1/num2);
}
Remove tripMPG[count] = answer(tripMiles, gallons); from right after the while loop and instead add the following line at the end of your while loop right before count++;:
tripMPG[count] = answer(tripMiles[count], gallons[count]);
So your while should look like this:
while (count <= 9){//start while
System.out.println("Enter a description of this trip");
tripName[count] = scan.next();
System.out.println("How many miles did you drive?");
tripMiles[count] = scan.nextDouble();
System.out.println("How many gallons of gas did you use on this trip");
gallons[count] = scan.nextDouble();
tripMPG[count] = answer(tripMiles[count], gallons[count]);
count++;
}//end while

Categories