Java Scanner is throwing some errors I haven't seen - java

When I try to run this bit of code that I wrote:
import java.util.Scanner;
public class F1Calc
{
public static void main(String args[])
{
System.out.println("The coefficient of friction of the " + getSurface() + " surface is " + getCoeff() + ". The mass of the ball was " + getMass() + " and the momentum of the ball was "+ getMomentum() + " Nm. The potential energy contained by the ball at the top of the .121 m high ramp was " + getPotEnergy() + " Joules.");
}
public static String getSurface()
{
Scanner kb = new Scanner(System.in);
System.out.println("What is the surface you are rolling the ball into?");
String surface = kb.nextLine();
kb.close();
return surface;
}
public static double getMass()
{
Scanner kb2 = new Scanner(System.in);
System.out.println("What is the mass of the ball in kilograms?");
double mass = kb2.nextInt();
kb2.close();
return mass;
}
public static double getPotEnergy()
{
double potEnergy = getMass() * .121 * 9.8;
return potEnergy;
}
public static double getMomentum()
{
double doublePE = 2 * getPotEnergy();
double doublePEOverMass = doublePE / getMass();
double velocity = Math.sqrt(doublePEOverMass);
double momentum = velocity * getMass();
return momentum;
}
public static double getCoeff()
{
double coeff = getPotEnergy() / (getMass() * 9.8);
return coeff;
}
}
The following is displayed on the console:
What is the surface you are rolling the ball into?
Tile
What is the mass of the ball in kilograms?
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at F1Calc.getMass(F1Calc.java:20)
at F1Calc.getPotEnergy(F1Calc.java:26)
at F1Calc.getCoeff(F1Calc.java:39)
at F1Calc.main(F1Calc.java:6)
Adding lines so that my post can be submitted. Adding lines so that my post can be submitted. Adding lines so that my post can be submitted. Adding lines so that my post can be submitted.

There is only one underlying InputStream used for Scanner so don't close it - doing so closes it for all future instances of the class making it impossible to read from the source

You do not want to open a new scanner and close it each time. Instead, just create it once.
I also fixed two other bugs in your code.
You were using nextInt() to read a double. This has been replaced with nextDouble().
You are asking the user to input mass multiple times. This has been fixed by caching the value of mass, so it is read from the user only once.
Here is the corrected code.
import java.util.Scanner;
public class F1Calc
{
// Cache the values so we don't have to keep bugging the user
static double mass;
static Scanner kb;
public static void main(String args[])
{
mass = -1;
kb = new Scanner(System.in);
System.out.println("The coefficient of friction of the " + getSurface() + " surface is " + getCoeff() + ". The mass of the ball was " + getMass() + " and the momentum of the ball was "+ getMomentum() + " Nm. The potential energy contained by the ball at the top of the .121 m high ramp was " + getPotEnergy() + " Joules.");
}
public static String getSurface()
{
System.out.println("What is the surface you are rolling the ball into?");
String surface = kb.nextLine();
return surface;
}
public static double getMass()
{
if (mass > 0) return mass;
System.out.println("What is the mass of the ball in kilograms?");
mass = kb.nextDouble();
return mass;
}
public static double getPotEnergy()
{
double potEnergy = getMass() * .121 * 9.8;
return potEnergy;
}
public static double getMomentum()
{
double doublePE = 2 * getPotEnergy();
double doublePEOverMass = doublePE / getMass();
double velocity = Math.sqrt(doublePEOverMass);
double momentum = velocity * getMass();
return momentum;
}
public static double getCoeff()
{
double coeff = getPotEnergy() / (getMass() * 9.8);
return coeff;
}
}

Related

Radius Variable Isn't Being Passed From Constructor

I'm supposed to be using a constructor to accept the radius of a circle as an argument then using various accessor and mutator methods to display the area, circumference, and diameter. When I input the value for radius, say 4, it says that the radius and all other values (area, circumference, diameter ) are 0.0. I'm new to java and wanna know what I'm missing.
// import scanner to read keyboard input
import java.util.Scanner;
class CircleCalculator
{
private double radius;
public CircleCalculator(double r)
{
radius = r;
}
public static void main(String[] args)
{
// declare the variable keyboard that can reference an object of the scanner class
// create a new Scanner object in the memory that reads from the input System.in
Scanner keyboard = new Scanner(System.in);
System.out.println("\nWelcome to Cam's Magic Circle Calculator!");
System.out.println("\nEnter the radius of your circle");
double r, a, d, c;
CircleData circledata = new CircleData();
System.out.println("\nThe measurements of a circle with the radius " + circledata.getRadius() + " are:\n" +
"\tArea: " + circledata.getArea() +" units squared\n" +
"\tDiameter: " + circledata.getDiameter() +" units\n" +
"\tCircumference: " + circledata.getCircumference() +" units\n");
}
public static class CircleData //create class for mutator and accessor methods
{
Scanner keyboard = new Scanner(System.in);
double r = keyboard.nextDouble();
CircleCalculator setRadius = new CircleCalculator(r);
final double pi = 3.1415;
private double radius, area, diameter, circumference;
private double getRadius()
{
return radius;
}
private double getArea()
{
area = pi * radius * radius;
return area;
}
private double getDiameter()
{
diameter = 2 * radius;
return diameter;
}
private double getCircumference()
{
circumference = 2 * pi * radius;
return circumference;
}
}
}
Gives:
Welcome to Cam's Magic Circle Calculator!
Enter the radius of your circle
4
The measurements of a circle with the radius 0.0 are:
Area: 0.0 units squared
Diameter: 0.0 units
Circumference: 0.0 units
Your current code is confused because of the nesting of your classes. I recommend following good code practices by separating them out into their own class files. Let CircleData handle the actual circle data and calculation and make CircleCalculator your overall program sequence logic.
CircleCalculator
import java.util.Scanner;
public class CircleCalculator
{
public static void main(String[] args)
{
System.out.println("\nWelcome to Cam's Magic Circle Calculator!");
System.out.println("\nEnter the radius of your circle");
Scanner keyboard = new Scanner(System.in);
CircleData circledata = new CircleData(keyboard.nextDouble());
keyboard.close();
System.out.println("\nThe measurements of a circle with the radius " + circledata.getRadius() + " are:\n" +
"\tArea: " + circledata.getArea() +" units squared\n" +
"\tDiameter: " + circledata.getDiameter() +" units\n" +
"\tCircumference: " + circledata.getCircumference() +" units\n");
}
}
CircleData (in separate file so methods are now public)
public class CircleData
{
final double pi = 3.1415;
private double radius, area, diameter, circumference;
public CircleData(double radius) {
this.radius = radius;
}
public double getRadius()
{
return radius;
}
public double getArea()
{
area = pi * radius * radius;
return area;
}
public double getDiameter()
{
diameter = 2 * radius;
return diameter;
}
public double getCircumference()
{
circumference = 2 * pi * radius;
return circumference;
}
}
Because radius fields from CircleCalculator and CircleData classes are two different fields. So, you cannot use the radius of CircleCalculator from CircleData because CircleData contains such field already.
CircleData actually shouldn't have the Scanner field, it breaks SRP https://en.wikipedia.org/wiki/Single-responsibility_principle.
I'd recommend writing it this way:
class CircleCalculator {
public static void main(String[] args) {
// declare the variable keyboard that can reference an object of the scanner class
// create a new Scanner object in the memory that reads from the input System.in
Scanner keyboard = new Scanner(System.in);
System.out.println("\nWelcome to Cam's Magic Circle Calculator!");
System.out.println("\nEnter the radius of your circle");
CircleData circledata = new CircleData(keyboard.nextDouble());
System.out.println("\nThe measurements of a circle with the radius " + circledata.getRadius() + " are:\n" +
"\tArea: " + circledata.getArea() + " units squared\n" +
"\tDiameter: " + circledata.getDiameter() + " units\n" +
"\tCircumference: " + circledata.getCircumference() + " units\n");
}
public static class CircleData //create class for mutator and accessor methods
{
final double pi = 3.1415;
private final double radius;
public CircleData(double radius) {
this.radius = radius;
}
private double getRadius() {
return radius;
}
private double getArea() {
return pi * radius * radius;
}
private double getDiameter() {
return 2 * radius;
}
private double getCircumference() {
return 2 * pi * radius;
}
}
}
The radius variable isn't being passed from constructor because you have defined the constructor in the CircleCalculator class but the methods for calculating the area, circumference, etc using the radius variable value are in different class.
CircleCalculator setRadius = new CircleCalculator(r);
Here, though setRadius has the value which user has entered but it's not being used.
CircleData circledata = new CircleData();
Here, the circledata is referencing nothing. The method calls
circledata.getRadius() , circledata.getArea() , circledata.getDiameter() , circledata.getCircumference() are actually returning the default value of double that is 0.0 because the radius variable default value is 0.0
Also, there should be only one public class in a class file whose name should match the class file name and that public class should have the public static void main(String[] args) method.

Compute Area of a circle

My program runs and after a few secs it just stops compiling. tried to assign input for the radius and it didn't worked. Would appreciate it if somebody can help me with explaining why my program fails to run.
package computearea;
import java.util.Scanner;
public class ComputeArea {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double radius = input.nextDouble();
System.out.println("Radius: " + radius);
double area;
area = radius* radius * 3.14159;
System.out.println("The area for the circle of radius " + radius + "is"
+ area);
}
}

have trouble with calling methods. what am i missing?

fix me plz. i get multiple error messages
"variable airSpeed_km might not have been initialized"
"variable width might not have been initialized"
"variable length might not have been initialized"
import java.util.Scanner;
public class V4_________1{
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
double KNOTS_TO_KMPHR;
double airSpeed_km;
double airSpeed_knots;
double width;
double length;
***// need to do something in the main but not sure what exactly***
airSpeed_knots = keyboard.nextDouble();
System.out.println("what is your current airspeed in knots?");
System.out.println("your current airspeed in km is: " + airSpeed_km + "your holding pattern width is: " + width + "your holding patter length is: " + length);
}
public static double getAirSpeed(double airSpeed_knots, double KNOTS_TO_KMPHR, double airSpeed_km)
{
KNOTS_TO_KMPHR = 1.852;
airSpeed_km = airSpeed_knots * KNOTS_TO_KMPHR ;
return airSpeed_km;
}
public static double calcPatternWidth(double width, double airSpeed_km)
{
width = (airSpeed_km) / (60 * Math.PI) * 2;
return width;
}
public static double calcPatternLength(double airSpeed_km, double length)
{
length = (airSpeed_km) / (60 * Math.PI) * 2 + ((airSpeed_km) / 60);
return length;
}
}
You declare:
double airSpeed_km;
And after use it:
System.out.println("your current airspeed in km is: " + airSpeed_km + "your holding pattern width is: " + width + "your holding patter length is: " + length);
without any assignment. So you get an error, you can prevent this by giving it a default value of 0 for example.
double airSpeed_km = 0;
(same goes for your other errors)
In Java, the compiler gets upset if a variable even MIGHT be used without a value.
So it is best practice to always give a value to variables when you first declare them.
Since you normally don't know the value a variable will have at the time of declaration, it is common practice to give it a value of zero.
So your declarations should look like this:
double KNOTS_TO_KMPHR=0;
double airSpeed_km=0;
double airSpeed_knots=0;
double width=0;
double length=0;
This will take care of all your "[] might not have been initialized" compiler errors.
Your code is in correct. Your cannot set variable when you pass them into a function. See both approaches and understand what going on.
You can do this:
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
double KNOTS_TO_KMPHR=1.852;
double airSpeed_knots;
System.out.println("what is your current airspeed in knots?");
airSpeed_knots = keyboard.nextDouble();
System.out.println("your current airspeed in km is: " + getAirSpeed(airSpeed_knots) + "your holding pattern width is: " + calcPatternWidth(getAirSpeed(airSpeed_knots)) + "your holding patter length is: " + calcPatternLength(getAirSpeed(airSpeed_knots));
}
public static double getAirSpeed(double airSpeed_knots)
{
return airSpeed_knots * KNOTS_TO_KMPHR ;
}
public static double calcPatternWidth(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2;
}
public static double calcPatternLength(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2 + ((airSpeed_km) / 60);
}
Or do this if you want to set variables:
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
double KNOTS_TO_KMPHR=1.852;
double airSpeed_knots;
System.out.println("what is your current airspeed in knots?");
airSpeed_knots = keyboard.nextDouble();
double airSpeed_km=getAirSpeed(airSpeed_knots);
double width=calcPatternWidth(airSpeed_km);
double length= calcPatternLength(airSpeed_km);
System.out.println("your current airspeed in km is: " + airSpeed_km + "your holding pattern width is: " + width + "your holding patter length is: " + length);
}
public static double getAirSpeed(double airSpeed_knots)
{
return airSpeed_knots * KNOTS_TO_KMPHR ;
}
public static double calcPatternWidth(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2;
}
public static double calcPatternLength(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2 + ((airSpeed_km) / 60);
}

Where to put Scanner class

As a new student to Java I have bean practicing writing methods and then calling them from a different class. I would like to know how to have the radius determined by user input. I understand I need to use the Scanner class but I'm not sure which class to import the Scanner in and where to put the following bit of code.
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
FIRST FILE - My Methods
package circle;
public class Circle {
private double radius;
final double pi;
public Circle(double radiusIn, double piIn) {
radius = radiusIn;
pi = piIn;
}
public double getRadius() {
return radius;
}
public double calculateDiameter() {
return radius + radius;
}
public double calculateCircumference() {
return 2 * pi * radius;
}
public double calculateArea() {
return pi * radius * radius;
}
}
SECOND FILE
package circle;
public class CircleTest {
public static void main(String[] args) {
Circle myCircle;
myCircle = new Circle(3, 3.14159);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter());
System.out.println("Circle circumference is "
+ myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
}
}
Typically you declare variables where you need them in this case that means in the main method where the rest of the user interaction takes place.
package circle;
public class CircleTest {
public static void main(String[] args) {
Circle myCircle;
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
myCircle = new Circle(radius);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter());
System.out.println("Circle circumference is "
+ myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
}
}
Also Math.PI is a much more accurate approximation of pi. Use that instead of relying on the user to pass in the correct value:
package circle;
public class Circle {
private double radius;
public Circle(double radiusIn) {
radius = radiusIn;
}
public double getRadius() {
return radius;
}
public double calculateDiameter() {
return radius + radius;
}
public double calculateCircumference() {
return 2 * Math.PI * radius;
}
public double calculateArea() {
return Math.PI * radius * radius;
}
}
Think of an Object as an object, like an apple or a toothbrush.
class Circle is a defintion of an Object; it's a description that attempts to match reality. The predefined Java Object is like anything you might find in reality, you can't call eat() on an Object (in the real world) because it might be an apple, but it might be a toothbrush (or a circle).
Therefore, place the code where it makes sense as if it were a real world object. You want to retrieve user input. Does a circle know how to read user input? No!
You call your other class CircleTest. But what it really is, is CircleCreationApplication; that might be a better name for it. In an application that creates circles, you would receive user input. So that is where the code can go. Once you have your user input, you can use that to create the circle.
package circle;
public class CircleCreationApplication {
public static void main(String[] args) {
Circle myCircle;
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
myCircle = new Circle(radius, 3.14159);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter());
System.out.println("Circle circumference is "
+ myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
userInput.close();
}
}
Note: #ratchetfreak's answer has some other good things. Please read that as well
I think the user interaction code goes into the main class. That's where you handle the workflow, depending on user input. What you actually want is to remove the hardcoded radius (3) and read the value from the user using the Scanner, right?
Then your code snippet goes in the main method, right before instantiating the Circle object.
public static void main(String [] args)
{
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
Circle myCircle;
myCircle = new Circle(radius, 3.14159);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter ());
System.out.println("Circle circumference is " + myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
}
You would want to import the scanner and add the code to the second file. Then you can use radius as argument to the Circle constructor instead of just 3.

BMI calculator errors

While doing an assignment for a BMI calculator I keep running into problems with the compiler and the method being used.
The assignment requires me to call a function double bmi to calculate the bmi. I am having problems getting the calling of the function correct. Any help would be great.
One of the errors:
Prog5.java:44: error: illegal start of expression
public static double calculateBmi(double height, double total) {
^
Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double avgweight,bmi,total,wReading;
int heightft,heightin,height,k;
String category,weightreading;
System.out.print("Enter the height(in feet and inches separated by spaces): ");
heightft = sc.nextInt();
heightin = sc.nextInt();
height = ((heightft*12)+heightin);
System.out.print("Enter the weight values separated by spaces followed by a negative number: ");
wReading = sc.nextDouble();
While (wReading >=0);
{
total = wReading+total;
Count++;
wReading = sc.nextDouble();
}
avgweight = 0;
total = 0;
weightreading = "Weight readings: " + wReading;
avgweight = total/Count;
public static double calculateBmi(double height, double total) {
{
double bmi = 0;
double total = 0;
double height = 0;
bmi = (height*703) / (total*total);
}
return bmi;
}
if ( bmi > 30)
category=("Obese");
else if (bmi >= 25)
category=("Overweight");
else if (bmi >= 18.5)
category=("Normal");
else {
category=("Underweight");
}
System.out.println("");
System.out.println("Height: "+ heightft + " feet " + heightin + " inches" );
System.out.println("Weight readings: "+ count);
System.out.println("Average weight: " + avgweight + "lbs");
System.out.println("");
System.out.printf("BMI: " + "%.2f", bmi);
System.out.println("");
System.out.println("Category: " + category);
System.out.println("");
}
private static void ElseIf(boolean b) { }
private static void If(boolean b) { }
}
The problem you mention is due to you beginning another method inside main. You instead want a structure something like:
public class Prog5
{
public static void main(String[] args)
{
// code here
}
public static double calculateBMI(double height, double total)
{
//other code
}
}
Your problem is that you are attempting to define a method (namely, public static double calculateBMi) inside a method (public static void main), and Java does not let you do that. (Basically, methods that aren't main need to be attached to a class.)
In the future, you may want to look around before asking this kind of question, since duplicate versions of this have been asked. Your question is basically: Function within a function in Java

Categories

Resources