[英]user input to create java program
I've tried creating codes to solve a quadratic formula but I've only succeeded in creating it for a specific formula. 我曾尝试创建代码来求解二次方公式,但仅针对特定公式成功创建了代码。 Is there any way I can be providing the variables a
, b
, c
by user input then the solution prints out? 有什么办法可以通过用户输入提供变量a
, b
, c
,然后打印出解决方案? The program also refuses to run on command prompt but can run in eclipse. 该程序还拒绝在命令提示符下运行,但可以在Eclipse中运行。 What might be the issue? 可能是什么问题?
Here it is. 这里是。
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");
}
}
}
One possibility to take user input is to use the paramater String [] args
. 接受用户输入的一种可能性是使用参数String [] args
。 The String [] args
contains the value pass to the program when you executed it like java -jar program.jar arg1 arg2 arg3
. String [] args
包含您在执行程序时传递给程序的值,例如java -jar program.jar arg1 arg2 arg3
。
In your case, you will need to check if the user pass 3 arguments to the program and if so then assigned thoses values to your variables. 对于您的情况,您将需要检查用户是否将3个参数传递给程序,如果是,则将这些值分配给变量。
Here is a little bit of code that might help, note that I didn't add the validation and you will need more validation to make sure that you sanitize the user input: 这里有一些代码可能会有所帮助,请注意,我没有添加验证,并且您将需要更多验证来确保对用户输入进行清理:
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");
}
}
}
EDIT: You will probably need to change your code to adapt to the fact that now a
b
and c
might not be what you were thinking. 编辑:您可能需要改变你的代码,以适应这样的事实,现在a
b
和c
可能不是你在想什么。
You can take dynamic inputs from users in following way too 您也可以通过以下方式获取用户的动态输入
Scanner in = new Scanner(System.in);
double a = in.nextDouble();
double b = in.nextDouble();
double c = in.nextDouble();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.