This is a problem for school
Write a method drivingCost() with input parameters drivenMiles, milesPerGallon, and dollarsPerGallon, that returns the dollar cost to drive those miles. All items are of type double. If the method is called with
50 20.0 3.1599
the method returns 7.89975.
Define that method in a program whose inputs are the car's miles/gallon and the gas dollars/gallon (both doubles). Output the gas cost for 10 miles, 50 miles, and 400 miles, by calling your drivingCost() method three times.
Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
System.out.printf("%.2f", yourValue);
The output ends with a newline.
Ex: If the input is:
20.0 3.1599
the output is:
1.58 7.90 63.20
Your program must define and call a method:
public static double drivingCost(double drivenMiles, double milesPerGallon, double dollarsPerGallon)
So far my code seems to make sense, but I keep getting this error, and I am not sure what it means,
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
Here is my code
import java.util.Scanner;
public class LabProgram {
public static double drivingCost(double drivenMiles, double milesPerGallon, double dollarsPerGallon) {
double totalCost = (dollarsPerGallon * drivenMiles) / milesPerGallon;
return totalCost;
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double milesPerGallon = scnr.nextDouble();
double dollarsPerGallon = scnr.nextDouble();
double drivenMiles = scnr.nextDouble();
System.out.printf("%.2f ", drivingCost(drivenMiles, milesPerGallon, dollarsPerGallon) * 10);
System.out.printf("%.2f ", drivingCost(drivenMiles, milesPerGallon, dollarsPerGallon) * 50);
System.out.printf("%.2f\n", drivingCost(drivenMiles, milesPerGallon, dollarsPerGallon) * 400);
}
}
drivenMiles is not one of the inputs, you provide it in the calls to drivingCost().
System.out.printf("%.2f ", drivingCost(10, milesPerGallon, dollarsPerGallon));
System.out.printf("%.2f ", drivingCost(50, milesPerGallon, dollarsPerGallon));
System.out.printf("%.2f\n", drivingCost(400, milesPerGallon, dollarsPerGallon));
The reason you are getting NoSuchElementException is that there are only two input parameters and you are trying to read three parameters.
To avoid this kind of errors, always check user input.
It can be done using hasNextDouble:
Scanner scnr = new Scanner(System.in);
double milesPerGallon = (scnr.hasNextDouble() ? sc.nextDouble() : 0.0;
Also always watch out Divison by Zero.
The code will throw a exception if milesPerGallon is zero. So, solve this using ternary operand:
double totalCost = (dollarsPerGallon * drivenMiles) / (milesPerGallon!=0?milesPerGallon:1);
Although the code above result into a correct result.
Changing to code below make a little more sense:
return (drivenMiles / (milesPerGallon!=0?milesPerGallon:1)) * dollarsPerGallon;
The correct code is:
import java.util.Locale;
import java.util.Scanner;
public class LabProgram {
public static double drivingCost(double drivenMiles, double milesPerGallon, double dollarsPerGallon) {
//Avoid Division by zero
return (drivenMiles / (milesPerGallon!=0?milesPerGallon:1)) * dollarsPerGallon;
}
public static void main(String[] args) {
//Fix user input to US number formats
Locale.setDefault(Locale.ENGLISH);
Scanner scnr = new Scanner(System.in);
double milesPerGallon = (scnr.hasNextDouble()) ? scnr.nextDouble() : 0.00;
double dollarsPerGallon = (scnr.hasNextDouble()) ? scnr.nextDouble() : 0.00;
System.out.printf("10mi: $%.2f " , drivingCost( 10, milesPerGallon, dollarsPerGallon));
System.out.printf("50mi: $%.2f " , drivingCost( 50, milesPerGallon, dollarsPerGallon));
System.out.printf("400mi: $%.2f\n", drivingCost(400, milesPerGallon, dollarsPerGallon));
}
}
Compile this with: javac LabProgram.java
Run this with: java LabProgram
Output:
20.0 3.1599
10mi: $1.58 50mi: $7.90 400mi: $63.20`
Although I'm too late here, still posting this for anyone struggling with this. The following code gave me the correct output:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Double milesPerGallon = 0.0;
Double dollarsPerGallon = 0.0;
Double gasCost = 0.0;
Double gasCost20 = 0.0;
Double gasCost75 = 0.0;
Double gasCost500 = 0.0;
milesPerGallon = scnr.nextDouble();
dollarsPerGallon = scnr.nextDouble();
gasCost = dollarsPerGallon / milesPerGallon;
gasCost20 = gasCost * 20;
System.out.printf("%.2f", gasCost20);
System.out.print(" ");
gasCost75 = gasCost * 75;
System.out.printf("%.2f", gasCost75);
System.out.print(" ");
gasCost500 = gasCost * 500;
System.out.printf("%.2f%n", gasCost500);
}
}
Related
This is my code:
import java.util.Scanner;
public class LabProgram {
public static double drivingCost(double drivenMiles, double dollarsPerGallon, double milesPerGallon)
{ double totalCost = 0;
totalCost = (drivenMiles / milesPerGallon) * dollarsPerGallon ;
System.out.printf("%.2f", totalCost);
System.out.print(" ");
return totalCost;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double milesPGallon;
double dollarsPGallon;
double driveMiles;
double drivingCost;
milesPGallon = input.nextDouble();
dollarsPGallon = input.nextDouble();
input.close();
drivingCost(10, dollarsPGallon, milesPGallon);
drivingCost(50, dollarsPGallon, milesPGallon);
drivingCost(400, dollarsPGallon, milesPGallon);
System.out.print("\r");
}
}
The output is: '1.58 7.90 63.20 ' and what I need is '1.58 7.90 63.20'. How can I remove the trailing space in the output? I have tried to use trim() and replace() neither has helped at all. I am new to Java and have been banging my head against the wall for the last day and a half trying to figure this out. Any assistance would be appreciated even if it is just a nudge in the correct direction. Thank you in advance.
drivingCost is printing a space every time you call it:
public static double drivingCost(double drivenMiles, double dollarsPerGallon, double milesPerGallon)
{
double totalCost = 0;
totalCost = (drivenMiles / milesPerGallon) * dollarsPerGallon ;
System.out.printf("%.2f", totalCost);
System.out.print(" "); // <-------- here!
return totalCost;
}
You can remove that line, and instead print a space between calls to drivingCost:
drivingCost(10, dollarsPGallon, milesPGallon);
System.out.print(" ");
drivingCost(50, dollarsPGallon, milesPGallon);
System.out.print(" ");
drivingCost(400, dollarsPGallon, milesPGallon);
Alternatively, add an extra parameter to drivingCost:
public static double drivingCost(double drivenMiles, double dollarsPerGallon, double milesPerGallon, boolean isLastCall)
{
double totalCost = 0;
totalCost = (drivenMiles / milesPerGallon) * dollarsPerGallon ;
System.out.printf("%.2f", totalCost);
if (!isLastCall) {
System.out.print(" ");
}
return totalCost;
}
And call it like this:
drivingCost(10, dollarsPGallon, milesPGallon, false);
drivingCost(50, dollarsPGallon, milesPGallon, false);
drivingCost(400, dollarsPGallon, milesPGallon, true);
TL:DR program compiles but results do not print out
Hi, I am working on this assignment for my 1st year programming class. Here is the question:
: In this problem, you need to compute compound interest for various interest rates and various time periods.
More precisely, this means that given an amount to invest and an interest rate (a specific amount above the prime interest
rate, which for this assignment is 1.00 percent), compute the amount of money an individual would have after n years.
The formula to calculate this is given by:
final amount = amount(1.0 + (prime+rate/100.0)^n)
we need to invoke another class in this assignment from a prebuilt so the class they gave us was
import java.util.*;
//DO NOT PUT OTHER METHODS IN THIS CLASS or make any changes to it
public class UserInteraction
{
public String getStringValueFromUser(String message)
{
String value = "";
Scanner input = new Scanner(System.in);
System.out.print(message + " : ");
value = input.nextLine();
return value;
}
//DO NOT PUT OTHER METHODS IN THIS CLASS or make any changes to it
public double getDoubleValueFromUser(String message)
{
double value = 0;
Scanner input = new Scanner(System.in);
System.out.print(message + " : ");
value = input.nextDouble();
return value;
}
//DO NOT PUT OTHER METHODS IN THIS CLASS or make any changes to it
public int getIntValueFromUser(String message)
{
int value = 0;
Scanner input = new Scanner(System.in);
System.out.print(message + " : ");
value = input.nextInt();
return value;
}
//DO NOT PUT OTHER METHODS IN THIS CLASS or make any changes to it
}
and my code is here
import java.util.*;
public class InterestRate
{
UserInteraction input = new UserInteraction();
public static void main (String[] args)
{
InterestRate program = new InterestRate();
program.execute();
}
void execute()
{
double initial_money = input.getDoubleValueFromUser("Your initial amount");
double prime_rate = input.getDoubleValueFromUser("Enter the Prime Rate");
double InterestRate = input.getDoubleValueFromUser("Enter the Interest Rate as a value above prime");
double time = input.getDoubleValueFromUser("Enter the length of the investment in years to a decimal");
double InterestRate2 = input.getDoubleValueFromUser("Enter the second Interest Rate as a value above prime");
Calculations (initial_money, prime_rate, InterestRate, time);
Calculations2 (initial_money, prime_rate, InterestRate2, time);
}
void finaltotal(double totalrate4, double totalrate4a, double initial_money, double prime_rate, double InterestRate, double time, double InterestRate2)
{
double final_amount = (initial_money * totalrate4);
double final_amounta = (initial_money * totalrate4a);
printWinnings(final_amount, initial_money, InterestRate, prime_rate, final_amounta, time);
}
double Calculations(double initial_money, double prime_rate, double InterestRate, double time)
{
double totalrate = prime_rate + InterestRate;
double totalrate2 = totalrate / 100.0;
double totalrate3 = totalrate2 + 1.0;
double totalrate4 = Math.pow(time, totalrate3);
return totalrate4;
}
double Calculations2(double initial_money, double prime_rate, double InterestRate2, double time)
{
double totalrate1a = prime_rate + InterestRate2;
double totalrate2a = totalrate1a / 100.0;
double totalrate3a = totalrate2a + 1.0;
double totalrate4a = Math.pow(time, totalrate3a);
//double final_amounta = initial_money * totalrate4;
return totalrate4a;
}
void printWinnings(double final_amount, double initial_money, double prime_rate, double InterestRate, double time, double final_amounta)
{
System.out.println(" The amount of money you can expect to get over the " + time + " years you invest will be " + final_amount + " with your initial investment of " + initial_money + " at an rate of " + InterestRate);
}
}
So I typed it all up, and the program compiles, but when I run it, nothing prints out.
Technically you didn't ask a question you made a statement. I assume you meant to ask why your program does not produce any output of results after the initial prompts for input.
If you follow the execution of your code it goes like this:
The main method is executed first:
public static void main(String[] args)
{
InterestRate program = new InterestRate();
program.execute();
}
As you can see your execute method is called from main, so now the execution goes here:
void execute() {
double initial_money = input
.getDoubleValueFromUser("Your initial amount");
double prime_rate = input
.getDoubleValueFromUser("Enter the Prime Rate");
double InterestRate = input
.getDoubleValueFromUser("Enter the Interest Rate as a value above prime");
double time = input
.getDoubleValueFromUser("Enter the length of the investment in years to a decimal");
double InterestRate2 = input
.getDoubleValueFromUser("Enter the second Interest Rate as a value above prime");
Calculations(initial_money, prime_rate, InterestRate, time);
Calculations2(initial_money, prime_rate, InterestRate2, time);
}
Before I move on I just want to mention that naming methods so that they begin with a capital letter violates accepted Java standard naming practice. Methods are always named using camel case and starting with lowercase. Similarly, naming variables in this manner also violates the naming conventions of Java. For example, InterestRate should be interestRate because otherwise it reads like a class name. Generally only constants use underscores between words so things like initial_money would be more consistent with naming convention if written as initialMoney.
Getting back to your code - from where we left off your logic flows into Calculations and Calculations2:
double Calculations(double initial_money, double prime_rate,
double InterestRate, double time) {
double totalrate = prime_rate + InterestRate;
double totalrate2 = totalrate / 100.0;
double totalrate3 = totalrate2 + 1.0;
double totalrate4 = Math.pow(time, totalrate3);
return totalrate4;
}
double Calculations2(double initial_money, double prime_rate,
double InterestRate2, double time) {
double totalrate1a = prime_rate + InterestRate2;
double totalrate2a = totalrate1a / 100.0;
double totalrate3a = totalrate2a + 1.0;
double totalrate4a = Math.pow(time, totalrate3a);
// double final_amounta = initial_money * totalrate4;
return totalrate4a;
}
Now you will notice none of these methods have any calls to System.out.print or System.out.println. This is why you don't see any output.
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;
}
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));
}
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;
}
}