error: incompatible types: String cannot be converted to double[]
polyval = usrIn.nextLine();
^
1 error
为什么这不起作用?我在做什么错了?
import java.util.Scanner;
public class MainApp
{
public static void main(String[] args){
Scanner usrIn = new Scanner(System.in);
double aval, bval, cval;
System.out.println("Please enter infromation for three polynomials of type ax^2+bx+c.");
System.out.println("Enter a, b, and c for polynomial 1:");
double[] polyval = new double[3];
polyval = usrIn.nextLine();
System.out.println("Enter a, b, and c for polynomial 2:");
double[] polyval2 = new double[3];
//polyval2 = usrIn.nextLine();
System.out.println("Enter a, b, and c for polynomial 3:");
double[] polyval3 = new double[3];
//polyval3 = usrIn.nextLine();
System.out.println("Enter a, b, and c for polynomial 3:"
+"\t1. Print All Polynomials"
+"\t2. Add Two Polynomials"
+"\t3. Factor Using Quadratic Formula"
+"\t4. Update a Polynomial"
+"\t5. Find Largest Polynomial"
+"\t6. Enter X and Solve"
+"\t7. Clear All Polynomials"
+"\t8. Exit the Program");
}
}
double[] polyval = new double[3];
polyval = usrIn.nextLine();
我该如何解决
error: incompatible types: String cannot be converted to double[]
polyval = usrIn.nextLine();
^
1 error
答案 0 :(得分:0)
usrIn.nextLine()
将返回一个字符串。如果要将其转换为double [],则需要首先通过在split
上使用space
来将字符串解析为数组(假设这是您输入的方式)。然后,对于数字的每个String
表示形式,您都必须将其转换为double
double[] polyval = new double[3];
String[] nextLine = usrIn.nextLine().split(" ");
for (int i = 0; i < nextLine.length; i++) {
polyval[i] = Double.parseDouble(nextLine[i]);
}
OR
double[] polyval = new double[3];
polyval = Arrays.stream(usrIn.nextLine().split(" ")).mapToDouble(Double::parseDouble).toArray();
这两种解决方案均未考虑到错误的输入,因此您将需要添加一些检查以确保输入的格式可接受。
例如:
在for
循环之前,您可以添加支票
if (nextLine.length != 3) {
System.out.println("input should have length of 3");
System.exit(1);
}