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 adouble
. This has been replaced withnextDouble()
. - You are asking the user to input
mass
multiple times. This has been fixed by caching the value ofmass
, 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;
}
}