为什么我的程序没有给我预期的输出?

时间:2019-07-07 01:27:32

标签: java

我有一个主要方法derivedSolver,该方法在被调用时提示用户输入(字符串)函数。我刚开始,所以它意味着采用简单的函数,例如“ 3x ^ 2”的形式。如果字符串不为null,则调用另一个方法Solve(),该方法将遍历字符串,分析每个索引,并将实例变量分配给字符串值,具体取决于它们是int还是char,以及int然后,实例变量将根据用户给出的值进行操作,以得出导数。但是,当我运行程序时,它给出了部分正确的答案;如果我输入3x ^ 4作为函数,它将给我_x ^ 3,其中指数正确地减去了1,并将变量放在正确的位置。但是,无论下划线是什么,我都会成为孟加拉字母的成员。

我在数组行中移动,更改了循环,并检查了实例变量的分配。我认为问题出在 “ leadCoefficient2 = leadCoefficient1 * power1”行。

import java.util.Scanner;
public class DerivativeSolver {

    private Scanner input = new Scanner(System.in);
    private String actualInput;
    private char variable;
    private int leadCoefficient1;
    private int power1;
    private int leadCoefficient2;
    private int power2;
    private String answer;

    /*
     * Starts the process of solving an derivative by prompting user
     * to enter a function. If function not empty, invoke the
     * solve method
     */
    public DerivativeSolver()
    {
        System.out.println("Please enter a function:");
        actualInput = this.input.nextLine();
        if(actualInput != null)
        {
            Solve();
        }
        else
        {
            System.out.println("Null function");
        }
    }
    
/*
 * Takes in a string and returns the derivative of it.
 */
    public String Solve()
    {
        for(int i = 0; i < actualInput.length(); i++)
        {
            if(Character.isDigit(actualInput.charAt(i)))
            {
            leadCoefficient1 = actualInput.charAt(i);
            }


            if(Character.isLetter(actualInput.charAt(i)))
            {   
                variable = actualInput.charAt(i);
            }

            if(actualInput.charAt(i)==('^'))
            {
                power1 = actualInput.charAt(i+1);
            }           

        }

        leadCoefficient2 = leadCoefficient1 * power1;
        power2 = power1 -1;
        char ch[] = 
        {(char)leadCoefficient2,variable,'^'(char)power2};
        answer = new String(ch);
        System.out.println(answer);
        return answer;  
    }

如果我输入一个简单的函数3x ^ 4,而不是获得正确的导数,我会得到一个孟加拉字母字符,前导系数应在该位置,然后是变量和正确地减小的指数。

0 个答案:

没有答案
相关问题