I'm doing the dreaded grade average problem for my class and have run into MANY hiccups, but this one seems to be the major one. I'm not able to pull the calculated average in my method to the toString. Here's the one method:
public void average() {
total = (((quiz1 + quiz2) / 40 * 25) + (midterm / 100 * 35) + (finalExam / 100 * 40));
DecimalFormat dec = new DecimalFormat("#.0");
dec.format(total);
return;
}
And I'm trying to get it here:
public String toString(){
return ("Grade Report:\n" ....+ "Total Score " + total + "\n" ....);
The average method shouldn't set anything - it should just return the average. You can then format this number in your toString method:
public double average() {
return (((quiz1 + quiz2)/40 * 25) +
(midterm/100 * 35) +
(finalExam/100 * 40));
}
public String toString(){
DecimalFormat dec = new DecimalFormat("#.0");
String averageString = dec.format(average();
return ("The average score is " + averageString); // just an example
}
Your average method has declared void as its return type. It should probably actually return the value it calculates:
public String average(){
total = (((quiz1 + quiz2)/40 * 25) + (midterm/100 * 35) + (finalExam/100 * 40));
DecimalFormat dec = new DecimalFormat("#.0");
return dec.format(total);
}
public String toString(){
return ("Grade Report:\n" + average() + "Total Score " + total + "\n" ....);
}
I see two mistakes:
You're not returning the result of your average method, when you probably should be as opposed to storing it into a field. That's easy enough to fix.
You're likely dividing integers; if we can presume that quiz1, quiz2, midterm and finalExam are all int, then you won't get a floating point result back.
The first fix is easy: remove the total field and replace it with a local variable. Then, return the result of the format.
String total = ...
return dec.format(total);
Next, to ensure you don't divide ints, place some decimals in your quotient.
String total = (((quiz1 + quiz2) / 40.0 * 25) + (midterm / 100.0 * 35) + (finalExam / 100.0 * 40));
Related
My code here is working fine but whenever I run it, it doesn't seem to round up and I don't know what to add and where to add it.
package com.mycompany.billofsale;
public class Billofsale {
public static void main(String[] args) {
double s = 12.49;
double p = 20.00;
double t = 0.13;
double result = s * t;
double result2 = s + result;
double result3 = p - (s + result);
System.out.println("The total is "+s
+ "\n The tax is "+result
+ "\n The total cost with tax is "+result2
+ "\n The change is "+result3);
}
}
You need to use DecimalFormat to format all the numbers that you want to print to the decimals that you want.
Try with this code:
double s = 12.49;
double p = 20.00;
double t = 0.13;
double result = s * t;
double result2 = s + result;
double result3 = p - (s + result);
DecimalFormat format = new DecimalFormat(".00");
format.setRoundingMode(RoundingMode.HALF_UP);
System.out.println("The total is " + s + "\n The tax is " +format.format(result) + "\n The total cost with tax is " + format.format(result2)
+ "\n The change is " + format.format(result3));
I want to use method from another class to append in my JTextArea (TEXT IS HERE in my code), how to do it?
SecondWindow() {
super("Mortage Loan Calculator");
setLayout(new FlowLayout(FlowLayout.LEFT, 20, 20));
tArea = new JTextArea(***TEXT IS HERE***, 30, 40);
scroll = new JScrollPane(tArea);
add(scroll);
setLocationRelativeTo(null);`
`And here is a method:
public void calcAnnuity(int years, int months, double amount, double rate){
double totalMonths = (12 * years) + months;
double partOfRate = rate / 12.0 / 100.0;
double tempAmount = amount;
double payment = amount * partOfRate * Math.pow(1 + partOfRate, totalMonths) / (Math.pow(1 + partOfRate, totalMonths) - 1); //mathematical formula
DecimalFormat decFormat = new DecimalFormat("#.##");
System.out.println(1 + " Payment = " + decFormat.format(payment) + "--- Left to pay: " + decFormat.format(amount));
for(int i = 2; i <= totalMonths; i++) {
tempAmount -= (payment - partOfRate * amount);
amount -= payment;
**textishere.append**(i + " Payment = " + decFormat.format(payment) + " --- Left to pay: " + decFormat.format(tempAmount));
}
}
Well, the easiest way would be to implement a public static method in your ClassA where the JTextArea is located.
public static setJTextAreaText(String text){
tArea.setText(text);
}
And in your ClassB you import ClassA and then call this method from your method calcAnnuity()
import ClassA;
public void calcAnnuity(int years, int months, double amount, double rate){
...
ClassA.setJTextAreaText('**textishere.append**');
}
I created a method that calculates and displays values of simple interest based on the amount of years. I want to show all years so for example if the years is 5, I want to show the value for years 1, 2, 3, 4, 5
This is my code so far
public static String numbers(String method, double principal, double rate, double years) {
double simpleInterest = principal + (principal * (rate / 100) * years);
String interest = "";
for (double digit = 1; digit <= years; digit++) {
if (method.equals("Simple")) {
interest = "Principal: $" + principal + ',' + " Rate: " + rate + "\n" + "Year Simple Interest Amount\n"
+ digit + "-->$" + simpleInterest;
}
}
return interest;
}
public static void main(String[] args) {
System.out.print(numbers("Simple", 5000, 5, 5));
}
My output is
Principal: $5000.0, Rate: 5.0
Year Simple Interest Amount
5.0-->$6250.0
But I want it to also display the previous years like
Principal: $5000.0, Rate: 5.0
Year Simple Interest Amount
1.0-->$5250.0
2.0-->$5500.0
3.0-->$5750.0
4.0-->$6000.0
5.0-->$6250.0
What do I need to do to display the previous years?
if (method.equals("Simple")) {
interest = "Principal: $" + principal + ',' + " Rate: " + rate + "\n" + "Year Simple Interest Amount\n"
+ digit + "-->$" + simpleInterest;
}
in the code above you are reassigning interest if method is equal to "simple". so, the last assigned value is returned.
use += to concatenate new results to interest or just return String[] containing each result as an individual element and then iterate over it.
public static String numbers(String method, double principal, double rate, double years)
{
String interest = "";
for (double digit = 1; digit <= years; digit++)
{
if (method.equals(Simple))
{
double simpleInterest = principal + (principal * (rate / 100) * digit);
interest += "Principal: $" + principal + ',' + " Rate: " + rate + "\n" + "Year Simple Interest Amount\n"
+ digit + "-->$" + simpleInterest;
}
}
return interest;
}
You have to calculate simpleInterest for every year simpleInterest = principal + (principal * (rate / 100) * digit); here digit represent year.
and also use += operator to concatenate results to interest and return it.
You can also use string concat() method
Here is the syntax of this method: public String concat(String s).
you can use it like this: interest = interest.concat(digit + "-->$" + simpleInterest + "\n");
public static String numbers(String method, double principal, double rate, double years) {
double simpleInterest = principal + (principal * (rate / 100) * years);
String interest = "";
System.out.println("Principal: $" + principal + ',' + " Rate: " + rate + "\n"+ "Year Simple Interest Amount\n");
for (double digit = 1; digit <= years; digit++) {
if (method.equals("Simple")) {
simpleInterest = principal + (principal * (rate / 100) * digit);
interest += digit + "-->$" + simpleInterest + "\n";
}
}
return interest;
}
public static void main(String[] args) {
System.out.print(numbers("Simple", 5000, 5, 5));
}
Output:
Principal: $5000.0, Rate: 5.0
Year Simple Interest Amount
1.0-->$5250.0
2.0-->$5500.0
3.0-->$5750.0
4.0-->$6000.0
5.0-->$6250.0
I'm trying to calculate the average of the student scores and as it stands I'm struggling with the calculation part.
In my assignment I was asked to caulculate the avg age of three students and avg. heigth of three students.
Could someone please guide me in the last line of this code, I apologize for the newbie question, really stuck and cannot come up with any solution to why it's not calculating my numbers.
public static void main(String[] args) {
// this method will display the scores of students
//variable declaration
int JasperAge = 20;
int JasperHeigth = (int) 175.5;
int PaulaAge = 25;
int PaulaHeigth = (int) 190.5;
int NicoleAge = 18;
int NicoleHeigth = (int) 165;
//output
Scanner output = new Scanner (System.in);
System.out.println("Name\t "+ " Age\t " + " Height (cm)\t");
System.out.println("\n");
System.out.println("Jasper\t "+JasperAge+" \t "+JasperHeigth);
System.out.println("Paula\t "+PaulaAge+" \t "+PaulaHeigth);
System.out.println("Nicole\t "+NicoleAge+" \t "+NicoleHeigth);
System.out.println("Average\t ((20 + 25 + 18) /3) \t ((175.5 + 190.5 + 165) /3)");
}
}
There are a few things wrong:
int JasperHeigth = (int) 175.5;
int PaulaHeigth = (int) 190.5;
int NicoleHeigth = (int) 165;
Given that these appear to be heights with decimal values, it is likely that you would want to store these as doubles instead of ints. When you declare a value like 175.5 as an integer, it is actually truncated to instead be 175. To store the full value of these numbers, you should instead define them as:
double JasperHeigth = 175.5;
double PaulaHeigth = 190.5;
double NicoleHeigth = 165;
Side note: the reason you had to cast those numbers using (int) was because 175.5 is actually a double literal instead of an int, which was what you declared the variable as before.
Next, this scanner definition line is never used:
Scanner output = new Scanner (System.in);
You would use the Scanner class to get input from the user. For instance, if you wanted the user to enter in some names or numbers. In this case, it doesn't look like you need to request any input from the user so this line can probably be deleted.
And lastly, the problem with displaying your output is in this line:
System.out.println("Average\t ((20 + 25 + 18) /3) \t ((175.5 + 190.5 + 165) /3)");
The problem is that by enclosing the numbers within quotation marks, your expected arithmetic will not be evaluated and instead just displayed to the user as character data. If you wanted to evaluate those expressions you could instead pull the math operations out of the quotation marks and concatenate them to the String data using the + operator:
System.out.println("Average\t" + ((20 + 25 + 18) /3) + "\t" + ((175.5 + 190.5 + 165) /3));
However, there are still a few things wrong with this. First, ((20 + 25 + 18) /3) will evaluate as integer division. It will reduce to 63/3 which is 21. However, it would also display 21 if you had 64/3 or 65/3, because integer division truncates the part of the number past the decimal point. To prevent truncation of your desired result, you can cast either one of the numbers in the numerator or denominator to double, or divide by a double literal such as 3.0. So something like this:
System.out.println("Average\t" + ((20 + 25 + 19) /3.0) + "\t" + ((175.5 + 190.5 + 165) /3.0));
Then finally, none of these numbers are actually using the variables you defined earlier, they are completely separate. If you want to actually average the variables you will need to substitute them into the expression like this:
System.out.println("Average\t" + ((JasperAge + PaulaAge + NicoleAge) /3.0) + "\t" + ((JasperHeigth + PaulaHeigth + NicoleHeigth) /3.0));
Summary
Here is a program with all my suggested edits:
public static void main(String[] args) {
// this method will display the scores of students
//variable declaration
int JasperAge = 20;
double JasperHeigth = 175.5;
int PaulaAge = 25;
double PaulaHeigth = 190.5;
int NicoleAge = 18;
double NicoleHeigth = 165;
System.out.println("Name\t "+ " Age\t " + " Height (cm)\t");
System.out.println("\n");
System.out.println("Jasper\t "+JasperAge+" \t "+JasperHeigth);
System.out.println("Paula\t "+PaulaAge+" \t "+PaulaHeigth);
System.out.println("Nicole\t "+NicoleAge+" \t "+NicoleHeigth);
System.out.println("Average\t" + ((JasperAge + PaulaAge + NicoleAge) /3.0) + "\t" + ((JasperHeigth + PaulaHeigth + NicoleHeigth) /3.0));
}
Your last line should probably be something like:
System.out.println("Average age: " + ((JasperAge + PaulaAge + NicoleAge) /3) + ". Average height: " + ((JasperHeigth + PaulaHeigth + NicoleHeigth) /3) ".");
Mind my calculations, but you get the idea.
Java's an object-oriented language. You might just be starting, but it's never too soon to learn about encapsulation:
public class Student {
private final String name;
private final int age; // bad idea - why?
private final double heightInCm;
public Student(String n, int a, double h) {
this.name = n;
this.age = a;
this.heightInCm = h;
}
public String getName() { return this.name; }
public int getAge() { return this.age; }
public double getHeightInCm() { return this.heightInCm; }
public String toString() {
return String.format("name: '%s' age: %d height: %10.2f (cm)", this.name, this.age, this.heightInCm);
}
}
You just have to make your last print like this:
System.out.println("Average\t " + ((20 + 25 + 18) /3) + "\t " + ((175.5 + 190.5 + 165) /3));
or even better use your variables:
System.out.println("Average\t " + ((JasperAge + PaulaAge + NicoleAge) /3) + "\t " + ((JasperHeigth + PaulaHeigth + NicoleHeigth) /3));
Okay so I have built a denomination counter for the Indian currency rupees. Say, if you enter Rs. 3453, it gives this output:
Rs 1000 notes: 3
Rs 500 notes: 0
Rs 100 notes: 4
Rs 50 notes: 1
Rs 20 notes: 0
Rs 10 notes: 0
Rs 5 notes: 0
Rs 2 coins: 1
Rs 1 coin: 1
But I want this output and eliminate all the zeros,
Rs 1000 notes: 3
Rs 100 notes: 4
Rs 50 notes: 1
Rs 2 coins: 1
Rs 1 coin: 1
Here's my code:
import java.io.*;
import javax.swing.JOptionPane;
public class denom {
public static void main(String[] args) throws IOException{
String totalRsString;
int totalRs;
totalRsString = JOptionPane.showInputDialog(null, "Enter amount to be converted", "Denomination Conversion", JOptionPane.INFORMATION_MESSAGE);
totalRs = Integer.parseInt(totalRsString);
//Calculations begin here
int thousand, fh, h, f, twenty, t, fi, tw, o;
thousand = totalRs/1000;
int bal = totalRs - (1000*thousand);
fh = bal/500;
bal = bal - (500*fh);
h = bal/100;
bal = bal - (100 * h);
f = bal/50;
bal = bal - (50*f);
twenty = bal/20;
bal = bal - (20*twenty);
t = bal/10;
bal = bal-(10*t);
fi = bal/5;
bal = bal - (5*fi);
tw = bal/2;
bal = bal - (2*tw);
o = bal/1;
bal = bal - (1*o);
//End of calculation
//Print work.
JOptionPane.showMessageDialog(null, "Total Entered is Rs." + totalRsString + "\n" + "\nThousand rupee notes: " + thousand + "\nFive Hundred Notes: " + fh + "\nHundred notes: " + h + "\nFifty notes: " + f + "\nTwenty notes: " + twenty + "\nTen notes: " + t + "\nFive notes: " + fi +
"\nTwo coins: " + tw + "\nOne coins: " + o);
}
}
Rather than building your string as a single expression of the form ... + ... + ..., you can use a StringBuilder (see Javadoc for java.lang.StringBuilder) to assemble it across several statements. For example, something like this:
JOptionPane.showMessageDialog(null, "foo: " + 17 + "\n" + "bar" + 18 + "\n");
can be rewritten like this:
StringBuilder message = new StringBuilder();
message.append("foo: ").append(17).append("\n");
message.append("bar: ").append(18).append("\n");
JOptionPane.showMessageDialog(null, message.toString());
By using this approach, you can wrap any of the individual "append" statements in an if-block that makes sure the value is nonzero before adding it to the string.
As an alternative, consider using an enum to hold the value, kind and count for each form of Currency:
private enum Kind {
Coins, Notes
};
private enum Currency {
// …
Ten(10, Kind.Notes),
Five(5, Kind.Notes),
Two(2, Kind.Coins),
One(1, Kind.Coins);
private int value;
private Kind kind;
private int count;
private Currency(int value, Kind kind) {
this.value = value;
this.kind = kind;
}
};
Then your convert() method can iterate through the Currency instances and return a List<Currency> that includes only non-zero counts.
private static List<Currency> convert(int amount) {
List<Currency> list = new ArrayList<>();
int balance = amount;
for (Currency currency : Currency.values()) {
// update currency.count
// update balance;
if (currency.count != 0) {
list.add(currency);
}
}
return list;
}
Finally, you can loop though the List<Currency> to print the result:
List<Currency> list = convert(3453);
for (Currency currency : list) {
System.out.println("Rs "
+ currency.value + " "
+ currency.kind + ": "
+ currency.count);
}
You need to build the output string step-by-step. If the corresponding number of coins or notes for that specific input is equal to zero, you should skip that element in the final string.
Something like:
string output = "Total Entered is Rs." + totalRsString + "\n";
if(thousand == 0){
output += "\nThousand rupee notes: " + thousand;
}
/* Here you will do the same for the rest of notes and coins */
JOptionsPane.showMessageDialog(null, output);
Well, this is a lazy solution. But it's up to you to implement it in a more elegant way.
try reducing the number of variables you are creating. See the ones which can be reused.
StringBuilder sb = new StringBuilder();
int totalRs = 5500;
int bal = totalRs;
int numNotes =0;
if ((numNotes =bal/1000) > 0){
sb.append("Rs 1000 notes: " + numNotes + "\n");
bal = bal - (1000 * numNotes);
}
if ((numNotes =bal/500) > 0) {
sb.append("Rs 500 notes: " + numNotes + "\n");
bal = bal - (500 * numNotes);
}