I am supposed to calculate the sum of three double numbers and get its average.
I am required to use the following two methods, no changing them:
getNumbers() which only gets the user inputs, no argument, no return. getAverage() which calculate the average of the three double numbers, returns the average, and has no argument.
My question is every time I run it on CMD, it shows that method does not work and will not print an output. For me to enter three numbers, and get its average at the end.
If someone can give me advice as to what I am doing wrong, it will be greatly appreciated.
import java.util.Scanner;
public class ComputeAverage{
double firstNum;
double secondNum;
double thirdNum;
double sum;
double average;
public void getNumbers(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your first number: ");
double firstNum = keyboard.nextDouble();
System.out.println("Enter your second number: ");
double secondNum = keyboard.nextDouble();
System.out.println("Enter your third number: ");
double thirdNum = keyboard.nextDouble();
Test.println("The average is: " + average);
}
public double getAverage(double firstNum, double secondNum, double thirdNum){
double average = firstNum + secondNum + thirdNum / 3;
return average;
}
}
While you should learn the operator precedence for Java, this comes from BOMDAS which applies to maths.
The / operator has higher precedence than + which means what you have is
double average = firstNum + secondNum + (thirdNum / 3);
most likely what you intended was
double average = (firstNum + secondNum + thirdNum) / 3;
Also I suspect you wanted to call this method as well.
Test.println("The average is: " + getAverage(firstNum, secondNum, thirdNum);
I would also turn all your fields into local variables to avoid confusion. Note: Your IDE should hint to you to do this and give you an auto-fix.
There are several issues in your code. First of all, it will not compile as Test is an unknown. You have also declared firstNum, secondNum and thirdNum as member variables, but they are also declared as local variables in getNumbers(). You have to decide to use member variables, or pass the values as arguments to getAverage().
The next thing is that / has precedence over +, so thirdNum / 3 will be calculated first.
It's not necessary, but I think it is better to type / 3.0 as the 3 will be converted to double anyway, just to be as clear as possible.
It could for example look like this:
import java.util.Scanner;
public class ComputeAverage{
double firstNum;
double secondNum;
double thirdNum;
public void getNumbers(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your first number: ");
firstNum = keyboard.nextDouble();
System.out.println("Enter your second number: ");
secondNum = keyboard.nextDouble();
System.out.println("Enter your third number: ");
thirdNum = keyboard.nextDouble();
}
public double getAverage(){
return (firstNum + secondNum + thirdNum) / 3.0;
}
public static void main(String[] args) {
ComputeAverage ca = new ComputeAverage();
ca.getNumbers();
System.out.println("The average is: " + ca.getAverage());
}
}
In here you don't have a main method which is the programe's entry point. And you have initialized 3 local variables inside getNumber() which is not visible to getAverage()
import java.util.Scanner;
public class ComputeAverage{
double firstNum;
double secondNum;
double thirdNum;
double sum;
double average;
public void getNumbers(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your first number: ");
this.firstNum = keyboard.nextDouble();
System.out.println("Enter your second number: ");
this.secondNum = keyboard.nextDouble();
System.out.println("Enter your third number: ");
this.thirdNum = keyboard.nextDouble();
}
public double getAverage(double firstNum, double secondNum, double thirdNum){
double average = (firstNum + secondNum + thirdNum )/ 3;
return average;
}
public static void main (String [] arg){
getNumbers();
getAverage( firstNum, secondNum, thirdNum);
Test.println("The average is: " + average);
}
}
3 thing you need to consider in order to make this code to work
need to call the System.out.println, or define a static method println in a class Test (you didnt post it, so I guess you dont have it)
average value is not going to update is value automatically, you need to call the method you defined... getAverage
dont forget the operator precedence in the getAverage
summarizing, you need to:
replace this:
Test.println("The average is: " + average);
with
System.out.println("The average is: " + getAverage(firstNum, econdNum, thirdNum));
and because of the operator precedence do this:
public double getAverage(double firstNum, double secondNum, double thirdNum){
double average = (firstNum + secondNum + thirdNum) / 3;
return average;
}
Related
import java.util.Scanner ;
public class CollinsHealthCalculator {
double ACTIVITY_FACTOR = 1.375;
public static void main (String[] args) {
newHealthCalcDescription ();
Scanner keyboard = new Scanner (System.in);
System.out.println ("What is your weight in pounds? ");
double weightlb = keyboard.nextDouble ();
System.out.println ("What is your height in inches? ");
double heightin = keyboard.nextDouble ();
System.out.println ("What is your age in years? ");
double ageYears = keyboard.nextDouble ();
double WEIGHT_KILOGRAMS = weightlb / 2.2;
double HEIGHT_METERS = heightin * .0254;
double weightkg = WEIGHT_KILOGRAMS;
double heightm = HEIGHT_METERS;
double computingBMI (BMI, weightkg, heightm);
maleBMR (heightm, weightkg, ageYears);
femaleBMR (heightm, weightkg, ageYears);
showResults (BMI, caloriesm, caloriesf);
public static newHealthCalcDescription () {
System.out.println("This calculator will determine your BMI "
+ "(Body Mass Index). While also it will determine the amount "
+ "of calories needed to maintain weight.");
}
//Computing the BMI
public static void computingBMI (double BMI, double weightkg, double heightm){
BMI = weightkg/(Math.pow(heightm, 2));
}
//Computing BMR for male and female
public static void maleBMR (double heightm, double weightkg, double ageYears) {
double HEIGHT_CENTIMETERS = heightm * 100;
double heightcm = HEIGHT_CENTIMETERS ;
double BMRForMales = 13.397 * weightkg + 4.799 * heightcm - 5.677 * ageYears + 88.362;
double caloriesm = Math.round(BMRForMales * 1.375);
}
public static void femaleBMR (double heightm, double weightkg, double ageYears) {
double HEIGHT_CENTIMETERS = heightm * 100;
double heightcm = HEIGHT_CENTIMETERS ;
double BMRForFemales = 9.247 * weightkg + 3.098 * heightcm - 4.330 * ageYears + 447.593;
double caloriesf = Math.round(BMRForFemales * 1.375);
}
public static void showResults (double BMI, double caloriesm, double caloriesf) {
//Show results
System.out.printf ("%nYour BMI is: %7.1f", BMI);
System.out.println ("A BMI between 18.5 to 24.9 is considered normal.");
System.out.println ();
System.out.println ("To maintain current weight:");
System.out.print ("Men need to eat " + caloriesm);
System.out.println (" calories per day.");
System.out.print ("Females need to eat " + caloriesf);
System.out.println (" calories per day.");
}
}
I'm trying to get the code to pass down statements but I'm new to programming and have no clue on how to go about getting method passed down to another method. I've tried researching everywhere but I've had little luck in finding any help. Please help so I can make my programm functional I'm excited to learn just need help.
You can try giving the variables the global scope(outside the method). You may learn about it here.
When you declare a variable inside a method (i.e. code block), it is local to that block. So you cannot use that variable in any other method. Here the best option for you to do is to declare the variable, i.e. like weightkg etc as class variables.
You can change the return type of the methods from void to double and store the returned result and send the results to other methods.
for eg.
public static double computingBMI (double BMI, double weightkg, double heightm){
return weightkg/(Math.pow(heightm, 2));
}
double average = calcAverage(grade1, grade2, grade3, grade4, grade5);
System.out.println("The average is: ");
determineGrade(average);
public static double calcAverage(int grade1, int grade2, int grade3, int grade4, int grade5) {
double average = (grade1 + grade2 + grade3 + grade4 + grade5) / 5;
return average;
}
I keep getting the error where it says determineGrade(average), The error says:
This method must return a result of type double
All your inputs are ints. So your result will be an int. You need to cast at least one int to double then your result would be a double as well.
double average = (double) (grade1 + grade2 + grade3 + grade4 + grade5) / 5
That's because in determineGrade you return nothing. You only print something, but return nothing. So, please make the return type of determineGrade void, or, at least make it return something in double.
Ok sorry, but the rest of the code comes as follows,
import java.util.*;
public class Stock
{
public static void main (String[] args)
{
int grade1=0;
int grade2=0;
int grade3=0;
int grade4=0;
int grade5=0;
// All of the below are gathering input from user
System.out.println("What is the first grade?");
Scanner input = new Scanner(System.in);
grade1=input.nextInt();
System.out.println("What is the second grade?");
Scanner input2 = new Scanner(System.in);
grade2=input.nextInt();
System.out.println("Whar is the third grade?");
Scanner input3 = new Scanner(System.in);
grade3=input.nextInt();
System.out.println("What is the fourth grade?");
Scanner input4 = new Scanner(System.in);
grade4=input.nextInt();
System.out.println("What is the fifth grade?");
Scanner input5 = new Scanner(System.in);
grade5=input.nextInt();
double average = calcAverage(grade1, grade2, grade3, grade4, grade5);
System.out.println("The average is: ");
determineGrade(average);
}
public static double calcAverage(int grade1, int grade2, int grade3, int grade4, int grade5)
{
double average = (grade1 + grade2 + grade3 + grade4 + grade5) / 5;
return average;
}
public static double determineGrade(double average)
{
if (average>90)
{
System.out.println("You got an A");
}
else if (average>=80)
{
System.out.println("You got a B");
}
else if (average>=70)
{
System.out.println("You got a C");
}
else if (average>=60)
{
System.out.println("You got a D");
}
else if (average<60)
{
System.out.println("You got an F");
}
}
}
I hope I'm posting in the right place.
I'm pretty new to Java (meaning this is only my third program besides 'hello world').
I have a tip calculator I'm working on for an assignment. I'm not getting an 'error' as such,
but the method for splitting the bill always seems to think each customer pays 'infinity'.
I have my program set up in two classes: tipCalc1 and tipCalc2 (no points for originality of course).
The program appears to run without issue besides the 'infinity' issue.
Here's what I have so far. Any assistance appreciated, thanks.
***TipCalc1 Class:***
import java.util.Scanner;
public class Tipcalc1
{
public static void main(String[] args)
{
System.out.println("Welcome to Tip Calculator! ");
TipCalc2 Calculator = new TipCalc2();
System.out.println("Please enter the bill amount: ");
TipCalc2.calBill();
System.out.println("What percentage would you like to tip?: ");
Calculator.percTip();
}
}
***And the tipCalc2 class which does the dirty work:***
import java.util.Scanner;
public class TipCalc2
{
static double bill;
double tip;
double total;
double split;
double splitPrompt;
double Y;
double N;
double billPerPerson;
static Scanner scan = new Scanner(System.in);
public static void calBill()
{
bill = scan.nextDouble();
}
public void percTip()
{
tip = scan.nextDouble();
if(tip<1)
{
total = bill * tip;
}
else total = bill * (tip/100);
System.out.println("Your total is: " + total);
Split();
}
public void Split()
{
System.out.println("Would you like to split the bill? ");
System.out.println("Enter 1 for YES or 0 for NO: ");
splitPrompt = scan.nextDouble();
if(splitPrompt == 0)
{
System.out.println("Your total is: " + total);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program");
}
if(splitPrompt == 1)
{
System.out.println("How many ways would you like to split the bill? ");
splitPrompt = scan.nextDouble();
billPerPerson = total / split;
System.out.println("Each person pays: " + billPerPerson);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program.");
}
else System.out.println("Invalid Entry");
}
}
The default value for split (because you have not initialized it with another value) is 0.0, therefore, when you do
billPerPerson = total / split;
you divide by 0.0, so you will get Infinity.
Notes:
Since your variable splitPrompt is double and computers doesn't store real values with a 100% accuracy, you shouldn't compare it with 0.0. Since this variable will store 0 or 1 for input, you can declare it as int, which will be accurate.
Try to follow Java naming conventions. Use mixedCase for methods/variables and use CamelCase for classes/interfaces.
In the method split(), you should use an if-else if-else structure:
if(splitPrompt == 0) {
...
}
else if(splitPrompt == 1) {
...
}
else {
...
}
Silly mistake.
Change
System.out.println("How many ways would you like to split the bill?
splitPrompt = scan.nextDouble();
to
System.out.println("How many ways would you like to split the bill?
split = scan.nextDouble();
since you never change split which, like all double variables, is initialized to 0.0.
Also, you should use ints where appropriate as not all of the numbers should be doubles. Or even better, use 'y' and 'n' chars.
Class TipCalc2
//Total = **bill** * (gets percentage in decimal 15 = 0.15) + **bill**
Line 18 needs to be:
total = bill * (tip / 100) + bill;
Line 36/37 needs to be:
split = splitPrompt = scan.nextInt();
billPerPerson = total / split;
//You're dividing billPerPerson = total by ZERO (split);
Line 36/37 original:
billPerPerson = total / split;
I'm trying to code a loan calculator. I seem to be having issues. I am trying to get an input from the user and validate the input. I know I am doing it wrong the problem is I'm scratching my head wondering how to do it right.
I get a red line on the d = getDouble(sc, prompt); and the i = getInt(sc, prompt); which I understand I don't have that coded correctly. I'm just unsure how to go about fixing it.
I also have to validate the continue statement which I wasn't to sure the best way to go about that and finally the instructor expects the code to be 80 lines or less which I am right about 80 lines. I guess I'm looking for a better way to do this but being new I'm scratching my head and I'm hoping someone can lend a hand.
As always I really appreciate the help.
import java.util.Scanner;
import java.text.NumberFormat;
public class LoanCalculator
{
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while(isValid == false);
{
d = getDouble(sc, prompt);
if (d <= min)
{
System.out.println("Error! Number must be greater tha 0.0");
}
else if (d >= max)
{
System.out.println("Error number must be less than 1000000.0");
}
else
isValid = true;
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isvalid = false;
while(isvalid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error! Number must be more than 0");
else if (i >= max)
System.out.println("Error! Number must be less than 100");
else
isvalid = true;
}
}
public static void main(String[] args)
{
System.out.println("Welcome to the loan calculator");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
int months = years * 12;
double monthlyPayment = loanAmount * interestRate/
(1 - 1/Math.pow(1 + interestRate, months));
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);
System.out.println("RESULST");
System.out.println("Loan Amount" + currency.format(loanAmount));
System.out.println("Yearly interest rate: " + percent.format(interestRate));
System.out.println("Number of years: " + years);
System.out.println("Monthly payment: " + currency.format(monthlyPayment));
System.out.println();
System.out.println("Continue? (y/n): ");
choice =sc.next();
System.out.println();
}
}
}
You haven't made the implementation of your getDouble(Scanner,String) and getInt(Scanner,String) that's why you're getting the red line.
since you already have a scanner, and prompt string change it to this
System.out.print(prompt);
d = sc.nextDouble();
and for the integer
System.out.print(prompt);
i = sc.nextInt();
I think getDouble and getInt are string functions so you would have to get a string first then call those methods. However, since you have a scanner, I assume you want to use that with the nextXXX methods:
Scanner sc = new Scanner (System.in);
double d = sc.nextDouble();
You can use this complete snippet for educational purposes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter your double: ");
double d = sc.nextDouble();
System.out.print("Enter your integer: ");
int i = sc.nextInt();
System.out.println("You entered: " + d + " and " + i);
}
}
Transcript:
Enter your double: 3.14159
Enter your integer: 42
You entered: 3.14159 and 42
Basically, the process is:
Instantiate a scanner, using the standard input stream.
Use print for your prompts.
Use the scanner nextXXX methods for getting the input values.
A little more assistance here, based on your comments.
In your main function, you have:
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0)
and that function has the prototype:
public static double getDoubleWithinRange(
Scanner sc, String prompt, double min, double max)
That means those variables in the prototype will be set to the values from the call. So, to prompt for the information, you could use something like (and this is to replace the d = getDouble(sc, prompt); line):
System.out.print(prompt);
double d = sc.nextDouble();
And there you have it, you've prompted the user and input the double from them. The first line prints out the prompt, the second uses the scanner to get the input from the user.
As an aside, your checks for the minimum and maximum are good but your error messages have hard-coded values of 0 and 100K. I would suggest that you use the parameters to tailor these messages, such as changing:
System.out.println("Error! Number must be greater tha 0.0");
into:
System.out.println("Error! Number must be greater than " + min);
That way, if min or max change in future , your users won't get confused :-)
I'll leave it up to you to do a similar thing for the integer input. It is your homework, after all :-)
I am having an issue with a method returning to the main method. It is saying that amount in "return amount" cannot be resolved to a variable. Where am I off on this??
This is the message I get:
Multiple markers at this line
- Void methods cannot return a
value
- amount cannot be resolved to a
variable
Here is the code:
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
amount = temp;
System.out.print((count + 1) + " " + temp);
}
{
return amount;
}
}
You curly braces are not correct. The compiler - and me - was confused about that.
This should work (at least syntactically):
import java.util.Scanner;
public class Investment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years));
}
public static double futureInvestmentValue(
double amount, double interest, int years) {
double monthlyInterest = interest / 1200;
double temp = 0;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest, years * 12));
amount = temp;
System.out.print((count + 1) + " " + temp);
return amount;
}
}
Remove amount from its own scope As a start. Also from the method futureInvestmentValue, you take in amount as an argument but the value is never modified so you're returning the same value being passed which is most likely not the desired outcome.
remove return amount from its own scope
the method futureInvestmentValue... You can't modify any of the parameters inside the method so you have to declare another variable besides amount inside the method (maybe it's the temp variable you keep using) and return that instead
when you return something, the return statement is always inside the method. Never outside it while inside its own braces (never seen this before...)
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years) {
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
System.out.print((count + 1) + " " + temp);
}
return amount;
}
}