我目前正在修改一个以前的Java程序,它通过将代码的一部分分解为方法并调用这些方法来完成相同的任务来计算二次公式类型的数学问题。目前我坚持创建一种方法来计算分子中的判别式。如所分配的,我应该有一个方法接收用户对a,b和c值的输入,但我不确定如何将这些值从一种方法转换到下一个应该使用这些值的方法计算。Java:将用户输入的变量从一种方法调用到另一种
我的导师希望我们将b和c变量输入到数组中,并且我知道现在的方式是将值放入数组中的一种非常人工的方式,但仍应该用于此目的。
这是我到目前为止,并感谢阅读。
编辑:我从头开始,我无法弄清楚如何正确地从我的方法返回的信息,以便在未来可以使用它。我不断收到方法参数不适用的错误。有任何想法吗?
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;
}
}
当你在main中调用'getValues'时,它返回'double []'。您需要使用'double [] userInput = getValues();'来捕获返回值。然后将其作为输入参数传递给'calcDisc()'。您需要将'calcDisc'的方法签名更改为'calcDisc(double [] userInput)'。 – DavidS 2015-02-10 03:45:23
如果您开始了解变量的“范围”,将来您会有更轻松的时间。谷歌“Java变量范围”了解更多。 – DavidS 2015-02-10 03:47:10
谢谢戴维,这很有道理。我目前正在课堂上学习范围。我会在第二种方法开始时捕获返回值吗?或者在第一个结尾? – 2015-02-10 03:49:41