2 method Exception in thread "main" java.util.NoSuchElementException - java

I keep getting the Exception in thread "main" java.util.NoSuchElementException error message. I have tried switching stuff around, but I keep having this problem
I have tried declaring the variables in different methods, but nothing is seeming to work.
import java.util.Scanner;
public class LabProgram {
public static double drivingCost(double drivenMiles, double milesPerGallon, double dollarsPerGallon) {
double totalCost = (drivenMiles / milesPerGallon) * dollarsPerGallon;
return totalCost;
}
public static void main(String[] args) {
double milesG;
double dollarsG;
Scanner scnr = new Scanner(System.in);
milesG = scnr.nextDouble();
dollarsG = scnr.nextDouble();
drivingCost(10.0, milesG, dollarsG);
milesG = scnr.nextDouble();
dollarsG = scnr.nextDouble();
drivingCost(50.0, milesG, dollarsG);
milesG = scnr.nextDouble();
dollarsG = scnr.nextDouble();
drivingCost(400.0, milesG, dollarsG);
}
}
The problem is:
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.
The input is: 20.0 3.1599
Expected output: 1.58 7.90 63.20

import java.util.Scanner;
public class LabProgram {
/* Define your method here */
public static double drivingCost(double drivenMiles, double milesPerGallon, double dollarsPerGallon) {
double totalCost = (dollarsPerGallon * drivenMiles / milesPerGallon);
return totalCost;
}
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
double milesPerGallon = scnr.nextDouble();
double dollarsPerGallon = scnr.nextDouble();
double drivenMiles = 1;
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 divided by milesPerGallon then multiplying by dollarsPerGallon will give you the price of gas per mile driven.
Note: drivenMiles just needs to be passed to drivingCost in this case. That is why the integers 10, 50 and 400 are added to call.
since drivingCost has the parameters milesPerGallon, dollarsPerGallon and drivenMiles in that order, you have to call the method with the same order of the parameters.
"%.2f" will get two decimals to the right. Adding \n will start a new line afterward.
import java.util.Scanner;
public class LabProgram {
public static double drivingCost(double milesPerGallon, double dollarsPerGallon, double drivenMiles) {
// calcuating the cost of gas
double totalCost = (drivenMiles / milesPerGallon) * dollarsPerGallon;
return totalCost;
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double milesPerGallon;
double dollarsPerGallon;
milesPerGallon = scnr.nextDouble();
dollarsPerGallon = scnr.nextDouble();
// order of the call to the method is important, printing cost of gas for 10, 50, and 400 miles
System.out.printf("%.2f ",drivingCost(milesPerGallon, dollarsPerGallon, 10));
System.out.printf("%.2f ",drivingCost(milesPerGallon, dollarsPerGallon, 50));
System.out.printf("%.2f\n",drivingCost(milesPerGallon, dollarsPerGallon, 400));
}
}

You are calling scnr.nextDouble(); six times in your main function. Make sure you provide six arguments of type double when running your program. Currently, you are passing less that six arguments and scnr.nextDouble(); is throwing the exception as it could not find the next argument of type double.

import java.util.Scanner;
public class LabProgram {
public static double drivingCost(double milesPerGallon, double dollarsPerGallon, double drivenMiles) {
return (drivenMiles / milesPerGallon) * dollarsPerGallon;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double milesPerGallon, dollarsPerGallon;
milesPerGallon = input.nextDouble();
dollarsPerGallon = input.nextDouble();
System.out.printf("%.2f ", drivingCost(milesPerGallon, dollarsPerGallon, 10));
System.out.printf("%.2f ", drivingCost(milesPerGallon, dollarsPerGallon, 50));
System.out.printf("%.2f\n", drivingCost(milesPerGallon, dollarsPerGallon, 400));
}
}

Related

Java netbeans issue

Please help me with this netbeans assignment code. I have been working on it for a few hours, and I don’t understand it.
Thanks!
I would avoid using raw user input for now, and just focus on creating a reusable method that does your calculation internally. There is no reason to cast to a float, because all the values should be floating-point values.
The calc method handles the calculation that you have copy-pasted three times.
public class CalculateHalfLife {
public static double calc(double amount, double halfLife, double hours) {
return amount / (Math.pow(2, (hours / halfLife)));
}
public static void main(String[] args) {
double amount = 100; // mg of caffeine
double halfLife = 6; // hours
double[] allHours = { 6, 12, 24 };
for (double hours : allHours) {
double output = calc(amount, halfLife, hours);
System.out.printf("After %.0f hours: %.2f mg\n", hours, output);
}
}
}
If you want to to support user input, you should prompt the user to enter input:
import java.util.Scanner;
public class CalculateHalfLife {
private static double amount = 100; // mg of caffeine
private static double halfLife = 6; // hours
private static double[] allHours = { 6, 12, 24 };
public static double calc(double amount, double halfLife, double hours) {
return amount / (Math.pow(2, (hours / halfLife)));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an amount: ");
float amount = sc.nextFloat();
System.out.println();
for (double hours : allHours) {
double output = calc(amount, halfLife, hours);
System.out.printf("After %.0f hours: %.2f mg\n", hours, output);
}
sc.close();
}
}

(HackerRank Day 2: Operators) Problem with Constructor

In this HackerRank challenge, I need to find the total meal cost by adding tip_percent which is 20% of the meal_cost and tax_percent which is 8% of the meal_cost and the meal_cost being $12. So the output must be a round number of 15 but my output comes out as $14.
It does seem to work properly with custom values like $12.50 for meal_cost which later totaled comes out as a rounded value of $16. What am I doing wrong here?
static double findMealTotal(double meal_cost, int tip_percent, int tax_percent) {
tip_percent = (int)(meal_cost * tip_percent)/100;
tax_percent = (int)(meal_cost * tax_percent)/100;
return meal_cost + tip_percent + tax_percent;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double meal_cost = scanner.nextDouble();
int tip_percent = scanner.nextInt();
int tax_percent = scanner.nextInt();
//changed solve to mealTotal
double mealTotal = findMealTotal(meal_cost, tip_percent, tax_percent);
System.out.println(Math.round(mealTotal));
scanner.close();
}
You are using integers. Integers are rounded, so you loose precision over the next calculation. Try using doubles and cast to int at the end.
static void Main(string[] args)
{
double cost = findMealTotal(12, 20, 8);
Console.WriteLine(cost.ToString());
}
static double findMealTotal(double meal_cost, int tip_percent, int tax_percent)
{
double tip = meal_cost * tip_percent / 100;
double tax = meal_cost * tax_percent / 100;
return meal_cost + tip + tax;
}
And don't reuse parameters inside your function. It is bad practice.

Basic Java, passing data between methods

I am new to Java and trying to make a basic body mass calculator.
My problem is I need to ask the questions, convert the measurements and then pass it to another method then display the results in a separate method.
I've added my code below but keep getting a 1.0 returned as the answer each time.
import java.util.Scanner;
public class calcBMI {
public static void main(String[] args)
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter weight in pounds: ");
double weightInPounds = keyboard.nextDouble();
double weightInKg = (weightInPounds / 2.2);
System.out.print("Enter height in inches: ");
double heightInInches = keyboard.nextDouble();
double heightInMeters = (heightInInches / 0.254);
double resultBMI = 1;
displayResults(resultBMI);
}
public static double bodyMassIndex(double weightInKg, double
heightInMeters)
{
double resultBMI = weightInKg / Math.pow(heightInMeters, 2) * 1.375;
return resultBMI;
}
public static void displayResults(double resultBMI)
{
System.out.printf("The calculated body mass index was: " + resultBMI);
System.out.println();
}
}
Updated code, now getting;
Enter weight in pounds: 180
Enter height in inches: 68
The calculated body mass index was: 1.1415618118905313E-5
BUILD SUCCESSFUL (total time: 3 seconds)
import java.util.Scanner;
public class calcBMI {
public static void main(String[] args)
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter weight in pounds: ");
double weightInPounds = keyboard.nextDouble();
double weightInKg = (weightInPounds / 2.2);
System.out.print("Enter height in inches: ");
double heightInInches = keyboard.nextDouble();
double heightInMeters = (heightInInches / 0.0254);
displayResults(bodyMassIndex(weightInKg, heightInMeters));
}
public static double bodyMassIndex(double weightInKg, double heightInMeters)
{
return (weightInKg / Math.pow(heightInMeters, 2));
}
public static void displayResults(double resultBMI)
{
System.out.printf("The calculated body mass index was: " + resultBMI);
System.out.println();
}
}
You are not calling the bodyMassIndex method in your code at all. Change
displayResults(resultBMI);
to
displayResults(bodyMassIndex(weightInKg, heightInMeters));
resultBMI equals 1, so of course the output would always be :
"The calculated body mass index was: 1"
Full code:
public static void main(String[] args) {
System.out.print("Enter weight in pounds: ");
double weightInPounds = keyboard.nextDouble();
double weightInKg = (weightInPounds / 2.2);
System.out.print("Enter height in inches: ");
double heightInInches = keyboard.nextDouble();
double heightInMeters = (heightInInches / 0.254);
// You can get rid of the resultBMI variable
displayResults(bodyMassIndex(weightInKg, heightInMeters));
}
You get 1.0 because you hard coded it as such.
Change this:
double resultBMI = 1;
To:
double resultBMI = bodyMassIndex(weightInKG, heightInMeters);
By the way, you could also have returned BMI directly in the method and there is no need to multiply by 1.375 anymore since you are already supplying weight in KG:
public static double bodyMassIndex(double weightInKg, double heightInMeters)
{
return (weightInKg / (heightInMeters*heightInMeters));
}
Add on:
Your conversion from inches to meters is wrong as well. It should be:
double heightInMeters = (heightInInches * 0.0254);

How do I use the return value from a method in another method different from the calling method?

I'm kinda new to to java and stumbled on a problem that needs me to do currency conversion declaring different methods for:
getting amount, getting conversion rate, doing the actual conversion and printing the outcome of the conversion
import java.util.*;
public class Conver {
public static void main(String[] args){
amountToConvert();
exchangeRate();
convert();
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(){
int x = amount*rate;
return x;
}
public void printResult(){
System.out.println(x);
}
}
Learn to use parameters in the methods. Change the convert() method so that it looks like this:
public static double convert(double amount, double rate){
int x = amount*rate;
return x;
}
In the method above, double amount and double rate are the parameters. Use variables to help pass in parameters to convert() in the main method:
public static void main(String[] args){
double amount1 = amountToConvert();
double rate1 = exchangeRate();
double result = convert(amount1, rate1);
printResult(result);
}
Hope this helps!
Pass returned values to the method convert:
import java.util.*;
public class Conver {
public static void main(String[] args){
double amount = amountToConvert();
double rate = exchangeRate();
double result = convert(amount, rate);
printResult(result);
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(double amount, double rate){
double x = amount * rate;
return x;
}
public void printResult(double x){
System.out.println(x);
}
}
Also, don't use double for money!
First off, you need to change the "receiving method" so that it takes an argument. A method like:
public static double convert() {}
that needs to take in a value for amount and rate, needs to have those added to the method signature:
public static double convert (double amount, double rate) {}
Putting the two comma separated values inside of the parens means that this method takes two values, doubles, as arguments. This makes those values available to use inside of that method.
Now that you have a method that can take the required arguments, you need to actually use that method in your code. When calling this method, you start out the same as with others:
convert(
but then you need to add in the arguments you are using:
double amount = amountToConvert();
double rate = exchangeRate();
convert(rate, amount);
If you want to avoid creating those two additional variables in main(), you can actually call those methods inside of your new method:
convert(amountToConvert(), exchangeRate());

Problems using constructors and getting methods for another class

So i keep getting errors when i try to run the user class saying double is required an no arguments are found. I'm getting errors on lines 17, 40, 42, 44, 46 and 48. They're all errors which say doubles are required. Answers in plain English would be appreciated.
My main class:
import java.util.Scanner;
public class ElectricityCalculatorUser {
//Main method
public static void main (String [] args) {
ElectricityCalculator myCalculator = new ElectricityCalculator();
Scanner input = new Scanner (System.in);
//Input the initial reading
double initialReading;
System.out.print ("What is the inital reading on your electricity meter in kwH? ");
initialReading = input.nextDouble ();
//Input the final reading
double finalReading;
System.out.print ("What is the final reading on your electricity meter in kwH? ");
finalReading = input.nextDouble ();
//Input the number of days
//between readings
double numberOfDays;
System.out.print ("How many days have passed between your initial and final reading? ");
numberOfDays = input.nextDouble ();
//Calculations
double totalElectricityUsed = myCalculator.totalElectricityUsed();
System.out.print ("Total electricity used = " + totalElectricityUsed);
double costOfElectricity = myCalculator.costOfElectricity();
System.out.print ("Cost of electricity = " + costOfElectricity);
double standingCharge = myCalculator.standingCharge();
System.out.print ("Standing charge = " + standingCharge);
double costBeforeVAT = myCalculator.costBeforeVAT();
System.out.print ("Cost before VAT is added = " + costBeforeVAT);
double VAT = myCalculator.VAT();
System.out.print ("Cost of VAT = " + VAT);
double totalCost = myCalculator.totalCost();
System.out.print ("Total cost = " + totalCost);
}
}
My class with all the methods:
public class ElectricityCalculator {
//Attributes
private double initialReading;
private double finalReading;
private double numberOfDays;
//Constructors
public ElectricityCalculator (double ir, double fr, double nod) {
initialReading = ir;
finalReading = fr;
numberOfDays = nod;
}
//Calculating total electricity used
public double totalElectricityUsed () {
return finalReading - initialReading;
}
//Calculating cost of electricity
public double costOfElectricity () {
return totalElectricityUsed * 0.175;
}
//Calculating standing charge
public double standingCharge (double numberOfDays) {
return numberOfDays * 0.25;
}
//Calculating cost before VAT is added
public double costBeforeVAT (double costOfElectricity, double standingCharge) {
return costOfElectricity + standingCharge;
}
//Cost of VAT
public double VAT (double costBeforeVAT) {
return costBeforeVAT * 0.05;
}
//Total cost of electricity used
//including VAT
public double totalCost (double costBeforeVAT, double VAT) {
return costBeforeVAT + VAT;
}
}
In java, if you don't write a constructor, a default constructor will be added automatically for you, and this constructor would be public and takes no argument.
Something like the following:
public ElectricityCalculator () {
}
However, when you define any constructors, the default constructor will be removed. And hence, the only constructor that you have in your class is
public ElectricityCalculator (double ir, double fr, double nod) {
initialReading = ir;
finalReading = fr;
numberOfDays = nod;
}
And therefore
ElectricityCalculator myCalculator = new ElectricityCalculator();
Doesn't match any constructors.
you can simply create the instance after getting the values required to construct the object
ElectricityCalculator myCalculator = new ElectricityCalculator(initialReading, finalReading, numberOfDays);
In addition to Sleiman Jneidi answer, you are calling functions, but dont provide any parameters, as the method definition demands:
double standingCharge = myCalculator.standingCharge();
need to be changed to:
double standingCharge = myCalculator.standingCharge(10.0); //example for 10 days
same problem in the lines 42, 44, 46, 48 of your code
public ElectricityCalculator (double ir, double fr, double nod);
public double standingCharge (double numberOfDays);
public double costBeforeVAT (double costOfElectricity, double standingCharge);
public double VAT (double costBeforeVAT);
public double totalCost (double costBeforeVAT, double VAT);
The constructor and these methods take arguments but you are trying to call them as if they did not.
For the constructor, you can simply move this line
ElectricityCalculator myCalculator = new ElectricityCalculator();
to after you take input from the user so you can pass in the arguments.
// pass arguments here
// v v v
... = new ElectricityCalculator( initialReading , finalReading , numberOfDays );
For the other methods you need to be passing in the results of interim calculations. For example VAT(...) takes a costBeforeVAT which I assume should be the return value of costBeforeVAT(... , ...).
double costBeforeVAT = ...;
// pass argument here
// v
double VAT = myCalculator.VAT( costBeforeVAT );
Note that in some cases you probably do not need these methods to have certain parameters, for example
public double standingCharge () {
return numberOfDays * 0.25;
}
because numberOfDays was already a member of the class ElectricityCalculator and
public double costBeforeVAT () {
return costOfElectricity() + standingCharge();
}
because these methods can be called directly instead of asking for their results to be passed in.
Related: "Passing Information to a Method or a Constructor".

Categories