Unknown Source in Java Eclipse - java

I keep getting this error message and I can't figure out whats going on. I keep getting the error message "Exception in thread "main" java.util.NoSuchElementException" and then is says that my scanners have an unknown source.
Any ideas what's going on?
package pizza;
import java.util.Scanner;
public class Pizza {
public static void main(String[] args) {
Double diameter;
Double radius;
Double cost;
Double area;
final Double costPerInch;
//Ask and enter diameter
System.out.println("What is the diameter?");
Scanner size = new Scanner(System.in);
diameter = size.nextDouble();
size.close();
radius = diameter / 2;
//Ask and enter price
System.out.println("What is the price of the pizza?");
Scanner price = new Scanner(System.in);
cost = price.nextDouble();
price.close();
//Calculate cost per inch
area = radius * Math.PI;
costPerInch = cost / area;
//Output results
System.out.println("The cost per inch of the pizza is" + costPerInch);

I compiled this and ran it. Here is you problem:
size.close();
Once that closes, it loses the scanner altogether. Comment out that line, and the code works.

Related

Assignment that I ran stops working after first InputDialog, how could I fix it?

import javax.swing.JOptionPane;
import java.util.Scanner;
public class ShippingCost
{
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
JOptionPane.showInputDialog("Please enter the length of your package: ");
double length=input.nextDouble();
JOptionPane.showInputDialog("Please enter the width of your package: ");
double width=input.nextDouble();
JOptionPane.showInputDialog("Please enter the height of your package: ");
double height=input.nextDouble();
double dimensions= length * width * height;
System.out.println("The total dimensions of your package is: " + dimensions);
double charge=0;
double surcharge;
double additionalCharge;
double totalCost;
Code compiles just fine, however running it as an application to test out the inputs is where I run into the issue that I have. First input box appears, then won't do anything else after hitting enter. I'm super new the Java and only stuck on this...
You should use the return value of JOptionPane.showInputDialog to get the user's inputs, e.g.
double length = Double.valueOf(JOptionPane.showInputDialog("Please enter the length of your package: "));
and so on.

How to solve a problem to match the expected output in Java?

The meal before tax and tip is 12.00, the tax percentage of the meal is 20% and the tip of the meal is 8%.
You need the use Scanner class to receive input from the user.
12.00
20
8
The expected output is:
15
I tried different ways especially with the code below but I'm getting different result. I can't get 15 as the expected out put.
enter public class MealSolution {
private static final Scanner scanner = new Scanner(System.in);
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.print("Enter cost of meal: ");
double meal_cost = scanner.nextDouble();
System.out.print("Enter the tip percent: ");
int tip_percent = scanner.nextInt();
System.out.print("Enter tax of meal: ");
int tax_percent = scanner.nextInt();
double tip = meal_cost * tip_percent/100;
double tax = meal_cost * tax_percent/100;
double cost = meal_cost + tip + tax;
long total_cost = Math.round(cost);
System.out.println(total_cost);
scanner.close();
}
}
To get the total cost, take the meal cost and add the tip and the tax.
double cost = meal_cost + tip + tax;

Comparing return values from two overloaded methods in an if statement (in main method)

So i'm new to java, we just started this language in my programming class about a month ago. Anyhow, we're on overloading methods right now (just started methods last week) and I'm having trouble with comparing the values of the return statements in the overloaded methods. My intention is to compare them in an if statement in the main method. I'm sure the answer is simple, but i can't find information on it in my textbook or online. Sorry about the sloppy indentation, I'm having trouble with the features on this website and it's the first time i've used it. would appreciate any help! Here is the program:
import java.util.Scanner;
public class pizzaCalculation {
public static void main(String[] args){
//create scanner
Scanner i = new Scanner(System.in);
//create sentinel while loop, initiate priceperinch for both pizzas
int sentinel = 1;
//create while loop
while(sentinel != 0){
//create input for round pizza
System.out.println("What is the price of the round pizza?");
double priceRound = i.nextDouble();
System.out.println("What is the radius?");
double radius = i.nextDouble();
pizzaPrice(radius, priceRound);
System.out.println("What is the price of the rectangular pizza?");
double priceRect = i.nextDouble();
System.out.println("What is the width and length of the rectangular pizza?");
double width = i.nextDouble();
double length = i.nextDouble();
pizzaPrice();
//create if statement to determine best deal
if (pricePerInchRound > pricePerInchRect){
System.out.println("The best deal is the round pizza which is $"+pricePerInchRound);
}else{
System.out.println("The best deal is the rectangular pizza is $"+pricePerInchRect);
}
//ask if user would like to do again
System.out.println("Would you like to do another calculation? Enter 1 for yes and 0 for no.");
sentinel = i.nextInt();
}
}
public static double pizzaPrice(double num1, double priceRound){
Scanner i = new Scanner(System.in);
//this is for round pizza
double areaRound = Math.PI * num1 * num1;
double pricePerInchRound = priceRound / areaRound;
return pricePerInchRound;
}
public static double pizzaPrice(double num1, double num2, double priceRect){
//this is for rectangular pizza
//create scanner
Scanner i = new Scanner(System.in);
double areaRect = num1 * num2;
double pricePerInchRect = priceRect / areaRect;
return pricePerInchRect;
}
}
So there are several issues:
You need to pass parameters to the second call of pizzaPrice() like this
pizzaPrice(width, length, priceRect);
You need to store results of method calls in variables like
pricePerInchRound = pizzaPrice(a, b);
pricePerInchRect = pizzaPrice(a, b, c);
You are calling pizzaPrice() but you need to store the resulting value in a variable so you can use it later (and pass the right parameters).
double pricePerInchRound = pizzaPrice(radius, priceRound);
and ...
double pricePerInchRect = pizzaPrice(width, length, priceRect);
Also, take care to name your method parameters better - num1, num2 aren't very descriptive. You could have used width, length.

Calculating price per square inch of a pizza in Java

I am writing a java program to calculate the area of of a pizza in one method and to calculate the price per square inch of a pizza in another method. I have the area method working, but am not getting any output when I try to calculate the price per square inch. I think it has something to do with calling the area() method in the ppsi method, but I'm not sure exactly what I'm doing wrong or how to correctly call the area method.
import java.util.Scanner;
public class Pizza {
public static void main(String[] args){
System.out.println("What is the size of your pizza in inches?");
System.out.println(area() + " square inches");
System.out.println("What is the price of your pizza?");
System.out.println(ppsi());
}
public static double area(){
Scanner keyboard = new Scanner(System.in);
double diameter = keyboard.nextDouble();
return (diameter / 2) * (diameter / 2) * Math.PI;
}
public static double ppsi(){
Scanner keyboard = new Scanner(System.in);
double price = keyboard.nextDouble();
return((area()) / price);
}
}
In your ppsi method, it calls area, which is going to prompt the user to enter ANOTHER value in AGAIN. Instead, prompt for these values first, then pass them into your method
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the size of your pizza in inches?");
double diameter = keyboard.nextDouble();
System.out.println(area(diameter) + " square inches");
double price = keyboard.nextDouble();
System.out.println("What is the price of your pizza?");
System.out.println(ppsi(diameter, price));
}
public static double area(double diameter){
//Scanner keyboard = new Scanner(System.in);
//double diameter = keyboard.nextDouble();
return (diameter / 2) * (diameter / 2) * Math.PI;
}
public static double ppsi(double diameter, double price){
//Scanner keyboard = new Scanner(System.in);
//double price = keyboard.nextDouble();
return((area(diameter)) / price);
}
This way, the methods are doing ONE job, not two
You are calling area again in ppsi method , why does you need it again to read?
I think you want some thing like below , i just modified your code:
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("What is the size of your pizza in inches?");
double inches=scanner.nextDouble();
double area=area(inches);
System.out.println(area + " square inches");
System.out.println("What is the price of your pizza?");
double price=scanner.nextDouble();
System.out.println(ppsi(area, price));
}
public static double area(double diameter){
return (diameter / 2) * (diameter / 2) * Math.PI;
}
public static double ppsi(double area, double price){
return((area) / price);
}
After you print the prompt for "what is the price..." Your program is expecting the user to enter a price, and then enter area again. If you enter two numbers after that prompt, I expect you'll see some output.

Java: Returning Multiple Values to Main Method In Order To Compute Total

The code is below. The program runs a series of calculations based on data input by the user. My problem is that for the most important thing I'm looking for, total kg CO2 emissions, I continually get an answer of 0.0. What I need is a sum of the individual total emissions as calculated in each method, i.e. the values which are printed with the following: System.out.println(trans); System.out.println(elec); and System.out.println(food);
The total should be something like 25040 or whatever, depending on the value of the inputs provided by the user, but I'm constantly getting a total of 0.0., which is obviously false. Could have something to do with the way I've initialized my variables, or something to do with the limitations of returning values from methods. I just don't know what to do. How should I tackle this? All help greatly appreciated!
import java.util.Scanner;
public class CarbonCalc {
public static void main(String[] args) {
double trans = 0;
double elec = 0;
double food = 0;
giveIntro();
determineTransportationEmission(null);
determineElecticityEmission(null);
determineFoodEmission(null);
calculateTotalEmission(trans, elec, food);
//printReport(trans, elec, food);
}
//Gives a brief introduction to the user.
public static void giveIntro() {
System.out.println("This program will estimate your carbon footprint");
System.out.println("(in metric tons per year) by asking you");
System.out.println("to input relevant household data.");
System.out.println("");
}
//Determines the user's transportation-related carbon emissions.
public static double determineTransportationEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will first begin with your transportation-related carbon expenditures...");
System.out.print("How many kilometres do you drive per day? ");
double kmPerDay = console.nextDouble();
System.out.print("What is your car's fuel efficiency (in km/litre)? ");
double fuelEfficiency = console.nextDouble();
System.out.println("We now know that the numeber of litres you use per year is...");
double litresUsedPerYear = 365.00 * (kmPerDay / fuelEfficiency);
System.out.println(litresUsedPerYear);
System.out.println("...and the kg of transportation-related CO2 you emit must be...");
//Final calculation of transportation-related kgCO2 emissions.
double trans = 2.3 * litresUsedPerYear;
System.out.println(trans);
System.out.println("");
return trans;
}
//Determines the user's electricity-related carbon emissions.
public static double determineElecticityEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will now move on to your electricity-related carbon expenditures...");
System.out.print("What is your monthly kilowatt usage (kWh/mo)? ");
double kWhPerMonth = console.nextDouble();
System.out.print("How many people live in your home? ");
double numPeopleInHome = console.nextDouble();
System.out.println("The kg of electricity-related CO2 you emit must be...");
//Final calculation of electricity-related kgCO2 emissions.
double elec = (kWhPerMonth * 12 * 0.257) / numPeopleInHome;
System.out.println(elec);
System.out.println("");
return elec;
}
//Determines the user's food-related carbon emissions.
public static double determineFoodEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will now move on to your food-related carbon expenditures...");
System.out.print("In a given year, what percentage of your diet is meat? ");
double meat = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is dairy? ");
double dairy = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is fruits and veggies? ");
double fruitVeg = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is carbohydrates? ");
double carbs = console.nextDouble();
//Final calculation of food-related kgCO2 emissions.
System.out.println("The kg of food-related CO2 you emit must be...");
double food = (meat * 53.1 + dairy * 13.8 + fruitVeg * 7.6 + carbs * 3.1);
System.out.println(food);
System.out.println("");
return food;
}
//Calculates total emissions across all sources.
public static double calculateTotalEmission(double trans, double elec, double food) {
System.out.println("Your total kg of CO2 emitted across all sources is equal to...");
double total = trans + elec + food;
System.out.println((double) total);
System.out.println("");
return total;
}
}
Ah!! Thank you very much Lyju. I did the following and it all worked well.
From this:
double trans = 0;
double elec = 0;
double food = 0;
To this:
double trans = determineTransportationEmission(null);
double elec = determineElecticityEmission(null);
double food = determineFoodEmission(null);
The second problem which popped up here had to do with not correctly passing the Scanner parameter to the multiple methods.
I fixed that by adding the following to the main method:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double trans = determineTransportationEmission(console);
double elec = determineElecticityEmission(console);
double food = determineFoodEmission(console);
giveIntro();
calculateTotalEmission(trans, elec, food);
}
And because I had three scanner objects, one for each method, I simply removed the Scanners in each and can now pass a single Scanner from my main method to each of the others.

Categories

Resources