package DerivativeFormulas;
import Variables.Variables;
import java.io.IOException;
public class PowerRule {
public static void main(String[] args) throws IOException {
//User inputs derivative equation
System.out.print("Enter the derivative - ");
Variables.userInputs = Variables.input.readLine().split("");
//Coefficient is put into the string array "userInputs"
Variables.coefficient = Integer.parseInt(Variables.userInputs[0]);
//User inputs the variable assigned to function
String x;
x = Variables.userInputs[1];
//User inputs power symbol "^"
String power;
power = Variables.userInputs[2];
Variables.polydeg = Integer.parseInt(Variables.userInputs[3]);
System.out.println((Variables.coefficient * Variables.polydeg) + x + power + (Variables.polydeg - 1));
}
}
我试着写一个程序,用幂规则求一个函数的导数。用户输入前导系数,然后输入变量,然后输入幂符号"^",然后输入变量的指数,其间不带任何空格。所有输入都在一行上。4x^2 outputs 8x^1
只有当用户输入的前导系数和指数小于10时,程序才会成功。每当我尝试输入系数或指数的两位数时,都会出现错误。通过将.split("")
更改为.split(" ")
,我可以通过在输入之间添加空格来使程序工作,但我不希望在输入之间有空格。例如,10x^10
将无法工作。我该如何解决这个问题?
这里也有一些变量。
package Variables;
import java.io.*;
public class Variables {
//Main user input
public static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
//User inputs get put into a string array
public static String userInputs[] = new String[4];
//Numbers
public static int coefficient;
public static int polydeg;
//Symbols
public static char e = 'e';
}
发布于 2018-10-16 07:36:02
由于表达式中的a
和b
可以是多位数,因此split()
可能不是最好的工具。您可以使用indexOf
和substring
函数来提取数字:
String temp = Example.input.readLine();
Example.userInputs[0] = temp.substring(0, temp.indexOf("x"));
Example.userInputs[1] = "x";
Example.userInputs[2] = "^";
Example.userInputs[3] = temp.substring(temp.indexOf("^") +1, temp.length());
https://stackoverflow.com/questions/52825655
复制相似问题