This question already has answers here:
Java: Calling a static method in the main() method
(4 answers)
Closed 5 years ago.
I'm trying to call a method from outside of the main method and I'm stumped on how to go about doing it. I may be going about this the wrong way. For instance, I'd like the user to enter in a temperature in Fahrenheit and then call the fahrenheitToCelsius method to do the conversion and return the converted temperature.
Here is what I have so far:
import java.util.Scanner;
public class Converter {
// conversions
private static final double GRAMS_PER_OUNCE = 28.3495;
private static final double CENTIMETERS_PER_FEET = 30.48;
public static double fahrenheitToCelsius (double f) {
return (f - 32) / 1.8;
}
public static double feetToCentimeters (double feet) {
return feet * CENTIMETERS_PER_FEET;
}
public static double ouncesToGrams (double ounces) {
return ounces * GRAMS_PER_OUNCE;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number in Fahrenheit: ");
System.out.print(in.nextDouble());
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number in Fahrenheit: ");
double far = in.nextDouble();
double cel = fahrenheitToCelsius (far);
System.out.println (cel);
}
Like this?
Related
This question already has answers here:
What is 'scope' in Java?
(2 answers)
Closed 2 years ago.
I am pretty new to coding and I have been having trouble with a Physics calculator I've been making. I made this trying to utilize OOP for a class project. The point I to let the user input the variables, then they get shipped into the equation on the class file, and then finally display the result. When I try to compile, it says that the function getAnswer can't see the result declared above it. I plan to make each of the 16 iterations of the equation, so I need to first figure out why this one doesn't work. Any answer is welcome.
-Thanks
import java.util.Scanner;
public class VFD {
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to Kinmatics calculator");
System.out.println("You can find Final Velocity, Acceleration, DIsplacemnt, or Time");
System.out.println("What variable is not included in the equation?");
String missing = keyboard.next();
System.out.println("What variable are you looking for?");
String find = keyboard.next();
if (missing.equals("Final Velocity") && find.equals("Initial Velocity")) {
System.out.println("Please enter your available values");
System.out.println("Acceleration = (m/s^2)");
double a = keyboard.nextDouble();
System.out.println("Displacement = (m)");
double d = keyboard.nextDouble();
System.out.println("Time = (s)");
double t = keyboard.nextDouble();
VelocityFinder qviadt = new VelocityFinder();
qviadt.qviadt(a, d, t);
System.out.println(qviadt.getAnswer());
}
}
}
This is the class file
public class VelocityFinder {
public void qviadt( double a, double d, double t ) {
double result = d/(.5*a*(t*t))/t;
double answer = result;
}
public String getAnswer () {
return answer;
}
}
public class VelocityFinder {
private double answer;
public void qviadt( double a, double d, double t ) {
double result = d/(.5*a*(t*t))/t;
double answer = result;
}
public String getAnswer () {
return String.valueOf(answer);
}
}
The methods qviadt and getAnswer are in the same class, but they are not the same method. getAnswer is trying to return something that doesn't exist. To fix this, remove getAnswer and change qviadt to:
public void qviadt( double a, double d, double t ) {
double result = d/(.5*a*(t*t))/t;
double answer = result;
return answer;
}
and store the return value of it directly. This is called a scope issue and you should look into what scope is and how to use it.
I'm having trouble using non static methods. I'm trying to get the value of my "side" variable from a method and plug them into another method which will calculate area. Is there a way to do this without changing the methods to static? None of the previously answered questions on here are helping and neither is my textbook.
import java.util.*;
public class CubeVolume
{
int side1;
int side2;
int side3;
public void getSides()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the length of side1");
side1 = input.nextInt();
System.out.println("Enter the length of side2");
side2 = input.nextInt();
System.out.println("Enter the length of side3");
side3 = input.nextInt();
}
public int getVolume(int side1, int side2, int side3)
{
int volume = side1 * side2 * side3;
return volume;
}
public static void main(String[] args)
{
CubeVolume cube = new CubeVolume();
cube.getSides();
cube.getVolume(side1, side2, side3);
}
}
I think the problem is with my method call cube.getVolume(side1, side2, side3); because the compiler tells me that non-static variable cannot be referenced from a static context.
If you want to use methods within main() then those methods must be static since main() is static. So you methods should be declared as:
public static void getSides() { .... }
public static int getVolume(int side1, int side2, int side3) { .... }
You can however avoid all this if you tell an instance of your class to start from a non-static method from within your main() method:
public static void main(String[] args) {
new CubeVolume().startApp(args);
}
private void startApp(String[] args) {
CubeVolume cube = new CubeVolume();
cube.getSides();
cube.getVolume(side1, side2, side3);
}
Now your other methods in the class do not need to be static since you're not calling them from static main().
There is no need to pass in any parameters to getVolume(), just use the class variables:
import java.util.Scanner;
class CubeVolume {
private int side1;
private int side2;
private int side3;
private void getSides() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the length of side1: ");
side1 = input.nextInt();
System.out.print("Enter the length of side2: ");
side2 = input.nextInt();
System.out.print("Enter the length of side3: ");
side3 = input.nextInt();
input.close();
}
private int getVolume() {
return side1 * side2 * side3;
}
private void printAppTitle() {
System.out.println("Cube Volume Calculator");
System.out.println("======================");
}
public static void main(String[] args) {
CubeVolume cube = new CubeVolume();
cube.printAppTitle();
cube.getSides();
String cubeVolumeString = String.valueOf(cube.getVolume());
System.out.println("The cubes volume is: " + cubeVolumeString);
}
}
Example Usage:
Cube Volume Calculator
======================
Enter the length of side1: 3
Enter the length of side2: 4
Enter the length of side3: 5
The cube's volume is: 60
Alternative approach which stores the side lengths in a double array, sides, and deals with possible invalid input in getSides():
import java.util.Scanner;
class CubeVolume {
private double[] sides;
CubeVolume() {
sides = new double[3];
}
private void getSides() {
Scanner scanner = new Scanner(System.in);
int currentSide = 0;
while (currentSide < sides.length) {
System.out.printf("Enter the length of side %d: ", currentSide + 1);
double nextSide = 0.0;
input:
while (scanner.hasNext()) {
if (scanner.hasNextDouble()){
nextSide = scanner.nextDouble();
if (nextSide > 0) {
sides[currentSide] = nextSide;
break input;
} else {
System.out.println("ERROR: Input number was too small.");
System.out.printf("Enter the length of side %d: ", currentSide + 1);
}
} else {
System.out.println("ERROR: Invalid input, please input a number.");
System.out.printf("Enter the length of side %d: ", currentSide + 1);
scanner.next();
}
}
currentSide++;
}
scanner.close();
}
private double getVolume() {
return sides[0] * sides[1] * sides[2];
}
private void printAppTitle() {
System.out.println("Cube Volume Calculator");
System.out.println("======================");
}
public static void main(String[] args) {
CubeVolume cube = new CubeVolume();
cube.printAppTitle();
cube.getSides();
String cubeVolumeString = String.format("%.2f", cube.getVolume());
System.out.println("The cube's volume is: " + cubeVolumeString);
}
}
Example Usage 2:
Cube Volume Calculator
======================
Enter the length of side 1: a
ERROR: Invalid input, please input a number.
Enter the length of side 1: -1.1
ERROR: Input number was too small.
Enter the length of side 1: 3.4
Enter the length of side 2: 4.7
Enter the length of side 3: 5.8
The cube's volume is: 92.68
You need not to pass sides parameters to get valume function because your sides variable will be available to get valume function.
I'm currently modifying a previous Java program that computes quadratic formula type math problems by breaking parts of my code down into methods and calling those methods to complete the same task. Currently I'm stuck on creating a method to calculate the discriminant in the numerator. As assigned, I'm supposed to have one method that receives user input for the a,b, and c values, but I'm not sure how to get those values from one method into the next that is supposed to use those values in calculations.
My instructor wants us to have the a b and c variables input into an array and I know the way it is now is a pretty manual way of putting values into an array, but should still work for this purpose.
Here is what I have thus far and thanks for reading.
EDIT: I've started again from scratch, I can't figure out how to properly return information from my methods so that the next can use it. I keep getting method argument not applicable errors. Any ideas?
import java.util.*;
public class QuadraticMethods {
public static void main(String[] args){
getValues();
calcDisc(userInput);
}
public static double[] getValues() {
double[] userInput;
userInput = new double[3];
Scanner kbd = new Scanner(System.in);
System.out.println("Fourth Assignment by MyNameHere");
System.out.println("Welcome to the quadratic formula computation tool.");
System.out.println("This tool will solve problems in the form of: a^x + bx + c.");
System.out.println("Please enter the values you would like for a, b, and c.");
for (int i = 0; i < userInput.length; i++) {
userInput[i] = kbd.nextDouble(); }
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
/*
System.out.println(aValue);
System.out.println(bValue);
System.out.println(cValue);
*/
return userInput;
}
public static double calcDisc(double[] userInput) {
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
double radicalValue = (Math.pow(bValue, 2) - (4*aValue*cValue));
System.out.println(radicalValue);
return radicalValue;
}
}
To get your current code to work, only a small change is required:
public static void main(String[] args) {
double[] userInput = getValues();
calcDisc(userInput);
}
Further these assignments are not actually used.
public static double[] getValues() {
// ...
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
// ...
}
Some other improvements could be:
The result should not be printed by the method that calculates it. You already declared the method the right way by returning the value. Now you should use the returned value and print the result in the calling method.
public static void main(String[] args) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
// ...
public static double calcDisc(double[] userInput) {
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
double radicalValue = (Math.pow(bValue, 2) - (4 * aValue * cValue));
return radicalValue;
}
Printing the banner should probably not be mixed with requesting the user input. Imagine, you would want to repeat the read/evaluate/print cycle:
public static void main(String[] args) {
while (true) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
}
would print the banner text every time. Isolating the responsibilities enables you to alter behaviour without affecting unrelated code.
public static void main(String[] args) {
printBanner();
while (true) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
}
private static void printBanner() {
System.out.println("Fourth Assignment by MyNameHere");
System.out.println("Welcome to the quadratic formula computation tool.");
System.out.println("This tool will solve problems in the form of: a^x + bx + c.");
}
Scanner should be closed after use. Java 7 try with resources will do that for you.
public static double[] getValues() {
double[] userInput;
userInput = new double[3];
try (Scanner kbd = new Scanner(System.in)) {
System.out.println("Please enter the values you would like for a, b, and c.");
for (int i = 0; i < userInput.length; i++) {
userInput[i] = kbd.nextDouble();
}
}
return userInput;
}
I need some help with a program for my programming class. It's a recursive program that takes a subtotal and a gratuity rate given by the user that outputs the full total and the gratuity cost. This is what I've got so far, and for some reason it just doesn't work:
import java.io.*;
import java.until.Scanner;
public class gratuity {
private double total;
private double subTotal;
private double gratRate;
private double newSubTotal;
private double newGratRate;
public static void main(String[] args) {
System.out.print("Enter the subtotal: ");
System.out.print("Enter the gratuity rate: ");
Scanner scan = new Scanner(System.in);
Scanner myScan = new Scanner(System.in);
double subtotal = scan.nextDouble();
double gratRate = myScan.nextDouble();
System.out.println("The Gratuity is: " + newSubtotal);
System.out.println("The Total is: " + Total);
}
public static double computeGratRate() {
double newGratRate = (gratRate/100);
return newGratRAte;
}
public static double computeNewSub() {
double newSubTotal - (subTotal * newGratRate);
return newSubTotal;
}
public static double computeTotal() {
double total = (newSubTotal + newGratRate);
return total;
}
}
If anyone would help me figure out how to fix it, I would be very grateful! Thank you!
A few things.
You are creating new variables called "subtotal" and "gratRate" in Main. These values override the member variables of the class.
Your problem won't compile anyway, because...
All your methods are static, which is OK, but these static methods are accessing non-static variables. Make all your member variables of this class static. (Or make everything outside of Main not static and then have "Main" be a stub to just create an instance of the gratuity class.
You need to import java.util.Scanner, not java.until.Scanner.
This line is a compiler error:
double newSubTotal - (subTotal * newGratRate);
I think you mean:
double newSubTotal = (subTotal * newGratRate);
That should be enough hints for now.... keep trying.
Did you mean:
import java.util.Scanner;
public class Gratuity {
private double subTotal;
private double gratRate;
public static void main(String[] args) {
Gratuity gratuity = new Gratuity();
System.out.print("Enter the subtotal: ");
Scanner scan = new Scanner(System.in);
gratuity.setSubTotal(scan.nextDouble());
System.out.print("Enter the gratuity rate: ");
Scanner myScan = new Scanner(System.in);
gratuity.setGratRate(myScan.nextDouble());
System.out.println("The new GratRate is: " + gratuity.getNewGratRate());
System.out.println("The New Sub is: " + gratuity.getNewSub());
System.out.println("The Total is: " + gratuity.getTotal());
}
public double getNewGratRate() {
return gratRate/100;
}
public double getNewSub() {
return getNewGratRate() * subTotal;
}
public double getTotal() {
return getNewSub() + getNewGratRate();
}
public double getSubTotal() {
return subTotal;
}
public void setSubTotal(double subTotal) {
this.subTotal = subTotal;
}
public double getGratRate() {
return gratRate;
}
public void setGratRate(double gratRate) {
this.gratRate = gratRate;
}
}
package presentvalue;
import java.util.Scanner;
public class PresentValue {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double P; // present value
double F; // future value
double r; // annual interest rate
double n; // number of years
P = presentValue();
F = futureValue();
r = annualInterest();
n = years();
System.exit(0);
}
public static double presentValue()
{
int input;
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the presnt value of you savings account?");
return keyboard.nextDouble();
}
public static double futureValue()
{
int input;
Scanner keyboard = new Scanner(System.in);
System.out.println("How much do you want in your account in the future?");
return keyboard.nextDouble();
}
public static double annualInterest()
{
int input;
Scanner keyboard = new Scanner(System.in);
System.out.println("What is youe bank's interest rate?");
return keyboard.nextDouble();
}
public static double years()
{
int input;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many years will the money in the bank?");
return keyboard.nextDouble();
}
public static double presentValue(double F, double r)
{
return F/(1+(r * r));
}
public static void show(double presentValue)
{
System.out.println(presentValue);
}
}
The question says write a method presentValue that preforms this calculation. The method should accept the future value, annual interest rate, and number of years as arguments. It should return the present value, which is the amount that you need to deposit today. Demonstrate the method in a program that lets the user experiment with different values for the formula's terms.
Here is the formula P = F/(1+r)^2
You will have to use Math.pow:
public static double presentValue(double future, double intrest, double years)
{
return future / Math.pow(1.0 + intrest, years);
}
Note that I added the amount of years. You stated two years, but I think you really want to have a parameter to specify the number of years, because, otherwise you wouldn't ask the user for an amount of years, right?