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);
}
Related
excepted output : 1/4,1/2,3/4,1,5/4,3/2
but my output is coming as in the decimal form . Please help how to print in the form of fraction only.
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(sum+" ");
}
}}
take input in form of string so it will take input in required format and split it by "/" i.e someString.spit("/").
after that make one for loop and take two number and in two different variable store it.
and then take division for both and print it by using "/" in between them.
public class NewClass {
public static void main(String[] args) {
System.out.println(convertype(0.75));
}
public static String convertype(double decimal){
int digitsAfterPoint = String.valueOf(decimal).length() - String.valueOf(decimal).indexOf('.')+1; // get the count of digits after the point // for example 0.75 has two digits
BigInteger numerator = BigInteger.valueOf((long)(decimal*Math.pow(10, digitsAfterPoint))); // multiply 0.75 with 10^2 to get 75
BigInteger denominator = BigInteger.valueOf((long)(Math.pow(10, digitsAfterPoint))); // 10^2 is your denominator
int gcd = numerator.gcd(denominator).intValue(); // calculate the greatest common divisor of numerator and denominator
if (gcd > 1 ){ // gcd(75,100) = 25
return String.valueOf(numerator.intValue()/gcd) +" / " + String.valueOf(denominator.intValue()/gcd); // return 75/25 / 100/25 = 3/4
}
else{
return String.valueOf(numerator) +" / " + String.valueOf(denominator); // if gcd = 1 which means nothing to simplify just return numerator / denominator
}
}
}
Wrote a method where you can convert double numbers to fraction. Use this to convert it and print as below,
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(toFraction(sum)+" ");
}
}
static String toFraction(double x) {
int w = (int) x;
int n = (int) (x * 64) % 64;
int a = n & -n;
return n == 0 ? w+"" : (w * (64 / a) + (n / a)) + "/" + 64 / a;
}
}
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;
}
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`?
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());
Merged with Java JOptionPane Output.
I am new to Java and I have been going crazy trying to get this to work.
I have been trying to get this Print Method to work for the last couple of hour but I just can't figure out what is wrong with it. I don't get any errors when I run it. I only want one output box to display after all of the calculations have been made.
I need to ask the user the following information and display the output for the following:
Number of loans to compare
House Price
Down Payment
My Problem: Something is a matter with my math and the output box is displaying more than once.
I greatly appreciate any help I can get with this. Thanks In Advance!
package javamortgagecalculator;
import javax.swing.JOptionPane;
public class JavaMortgageCalculator {
public static void main(String[] args) {
int numberOfLoans;
double sellingPrice;
double downPayment;
double loanAmount;
double annualInterestRate = 0.0;
int numberOfYears = 0;
double[] interestRatesArr;
int[] numberOfYearsArr;
double[] monthlyPayment;
//A. Enter the Number Of Loans to compare and Convert numberOfLoansString to int
String numberOfLoansString = JOptionPane.showInputDialog("Enter the Number Of Loans to Compare");
numberOfLoans = Integer.parseInt(numberOfLoansString);
//B. Enter the Selling Price of Home Convert homeCostString to double
String sellingPriceString = JOptionPane.showInputDialog("Enter the Loan Amount");
sellingPrice = Double.parseDouble(sellingPriceString);
//C. Enter the Down Payment on the Home
String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home");
downPayment = Double.parseDouble(downPaymentString);
//Get the loanAmount by Subtracting the Down Payment from homeCost
loanAmount = sellingPrice - downPayment;
interestRatesArr = new double[numberOfLoans];
numberOfYearsArr = new int[numberOfLoans];
monthlyPayment = new double[numberOfLoans];
int counter = 1;
for (int i = 0; i < numberOfLoans; i++) {
//Enter the Interest Rate
String annualInterestRateString = JOptionPane.showInputDialog("Enter the interest rate for Scenario " + counter);
annualInterestRate = Double.parseDouble(annualInterestRateString);
interestRatesArr[i] = (annualInterestRate);
//D2 Get the number of years
String numberOfYearsString = JOptionPane.showInputDialog("Enter the number of years for Scenario " + counter);
numberOfYears = Integer.parseInt(numberOfYearsString);
numberOfYearsArr[i] = (numberOfYears);
counter++;
}
printArray(numberOfLoans,
sellingPrice,
downPayment,
loanAmount,
annualInterestRate,
numberOfYears,
interestRatesArr,
numberOfYearsArr,
monthlyPayment);
}
//public static void printArray(int numOfLoans, double price, double dwnPayment, double loanAmt, double[] printRate, int[] printYears) {
public static void printArray(int numberOfLoans2,
double sellingPrice2,
double downPayment2,
double loanAmount2,
double annualInterestRate2,
int numberOfYears2,
double[] interestRatesArr2,
int[] numberOfYearsArr2,
double[] monthlyPayment2){
for (int i = 0; i < numberOfLoans2; i++) {
//Calculate monthly payment
double monthlyPayment = loanAmount2 * annualInterestRate2 / (1 - 1 / Math.pow(1 + annualInterestRate2, numberOfYears2 * 12));
//Format to keep monthlyPayment two digits after the decimal point
monthlyPayment = (int) (monthlyPayment * 100) / 100.0;
//Store monthlyPayment values in an array
monthlyPayment2[i] = (monthlyPayment);
//Calculate total Payment
double totalPayment = monthlyPayment2[i] * numberOfYears2 * 12;
//Format to keep totalPayment two digits after the decimal point
//totalPayment = (int) (totalPayment * 100) / 100.0;
//totalPaymentArray[i] = (totalPayment);
StringBuilder sb = new StringBuilder();
int n = 0;
for (int x = 0; x < numberOfLoans2; x++) {
if (n == 0) {
sb.append(String.format("%s\t\t %s\t\t %s\t\t %s\t\t %s\t\t %s\t\t %n", "Selling Price", "Down Payment", "Loan Amount", "Rate", "Years", "Payment"));
}
sb.append(String.format("%s\t\t\t\t %s\t\t\t\t\t\t %s\t\t\t\t\t\t\t\t %s\t\t\t\t\t\t\t\t %s\t\t\t\t\t\t %s\t\t\t\t %n", "$" + sellingPrice2, "$" + downPayment2, "$" + loanAmount2, interestRatesArr2[i] + "%", numberOfYearsArr2[i], "$" + monthlyPayment2[i]));
n++;
}
String toDisplay = sb.toString();
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
}
}
}