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.
Related
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?
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am writing a Java program to decide how much a user has to pay for a delivery charge for a school project. I have been advised the method that works out the cost has to be static. When i de-bug my code the value of the price is never changing and i don't know why, please see my code below.
main method
package questionOne;
import java.util.Scanner;
import questionOne.DeliveryMenu;
public class DeliveryMenuDemo {
public static void main(String[] args)
throws java.io.IOException {
String choice;
DeliveryMenu d = new DeliveryMenu();
System.out.println("Enter the type of Delivery service needed (Standard/Super/WowWee)?");
Scanner scanner = new Scanner(System.in);
choice = scanner.next();
d.setDeliveryCost(choice);
d.getPrice();
}
}
and class with other methods
package questionOne;
public class DeliveryMenu {
private static String delivery;
private static int price=0;
public static int setDeliveryCost(String choice) {
if(delivery == "Standard") {
price = price + 22;
} else if (delivery == "Super") {
price = price + 44;
} else if (delivery == "wow-wee") {
price = price + 60;
}
return price;
}
public String setDelivery(String s) {
return delivery=s;
}
public void getPrice() {
System.out.println(price);
}
}
price is never changing to the desired amount.
For comparing Strings you need to use String method equals.
(delivery.equals("Standard")) or (delivery.equalsIgnoreCase("Standard")) instead of (delivery == "Standard")
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());
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;
}
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?