gpt4 book ai didi

java - 用户输入创建java程序

转载 作者:行者123 更新时间:2023-12-01 07:10:25 29 4
gpt4 key购买 nike

我尝试创建代码来求解二次公式,但我只成功地为特定公式创建了它。有什么方法可以通过用户输入提供变量 abc 然后打印出解决方案?该程序也拒绝在命令提示符下运行,但可以在 eclipse 中运行。可能是什么问题?

就是这里。

public class Equationsolver {

public static void main(String[] args) {
double a, b, c;
a = 2;
b = 6;
c = 4;

double disc = Math.pow(b,2) - 4*a*c;
double soln1 = (-b + Math.sqrt(disc)) / (2*a) ;
double soln2 = (-b - Math.sqrt(disc)) / (2*a);
if (disc >= 0) {
System.out.println("soln1 = " + soln1);
System.out.println("soln2 = " + soln2);
}else{
System.out.println("equation has no real roots");
}

}

}

最佳答案

获取用户输入的一种可能性是使用参数String [] argsString [] args 包含执行程序时传递给程序的值,如 java -jar program.jar arg1 arg2 arg3

在您的情况下,您需要检查用户是否向程序传递了 3 个参数,如果是,则将这些值分配给您的变量。

这里有一些代码可能会有所帮助,请注意,我没有添加验证,您将需要更多验证来确保清理用户输入:

public class Equationsolver {

public static void main(String[] args) {
double a, b, c;
a = Double.parseDouble(args[0]); //Here it will get the first argument pass to the program
b = Double.parseDouble(args[1]);
c = Double.parseDouble(args[2]);

double disc = Math.pow(b,2) - 4*a*c;
double soln1 = (-b + Math.sqrt(disc)) / (2*a) ;
double soln2 = (-b - Math.sqrt(disc)) / (2*a);
if (disc >= 0) {
System.out.println("soln1 = " + soln1);
System.out.println("soln2 = " + soln2);
}else{
System.out.println("equation has no real roots");
}

}

}

编辑:您可能需要更改代码以适应这样的事实:现在 a bc 可能不是您想要的正在思考。

关于java - 用户输入创建java程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15554881/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com