我正在尝试创建一个方法,该方法将返回数字中每个双 x 的 n 次根之和,其中数字由零个或多个双标记(用空格分隔)组成,并且 n 为正数。
示例:sumOfRoots("1.0 4.0 9.0 16.0", 2) 为 10,sumOfRoots("", 3) 为 0。
public static double sumOfRoots (String numbers, int n)
{
Scanner scanner = new Scanner(numbers);
Scanner b = scanner.useDelimiter(" ");
int y = b.nextInt();
double x = 0;
while (b.hasNextDouble())
{
x = x + (y ^ (1 / n));
}
return x;
}
但我不断抛出输入不匹配错误。知道我可以改变什么来使它工作吗?
最佳答案
如果您想使用Scanner
,您的代码可以这样修复:
public static double sumOfRoots(String numbers, int n){
Scanner scanner = new Scanner(numbers);
double sum = 0;
while(scanner.hasNextDouble())
sum += Math.pow(scanner.nextDouble(), 1d / n);
return sum;
}
在 Java 中 ^ 不是指数运算符(如注释中所述),因此您必须使用 Math.pow()
关于java - 如何在 while 循环中使用扫描仪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57929977/