Командная строка Java не распознает строку

Мой код работает нормально, но это то, что меня убивает, и я не могу найти ответ. Я не могу передать строку непосредственно из аргументов командной строки в свой конструктор, чтобы затем передать ее методу (evaluateMethod), вызываемому во время построения. По какой-то причине метод не видит его как строку. Почему оно это делает? Единственный способ заставить его работать - это поместить операторы if/else в мой основной метод, который вызывает конструктор и передает аргументы. Прилагается мой код.

/**
 * Program to calculate approximation, actual value, absolute error, and relative error with a definite integral
 * @author c-dub
 *
 */
public class Integrate {
    private String whichWay;
    double upper, lower, deltaX, actual, absoluteError, relativeError;  
    int rect;   

    // Constructor
    Integrate(String str, double a, double b, int n) {
        this.whichWay = str;
        this.lower = a;
        this.upper = b;
        this.rect = n;
        this.deltaX = (b - a) / rect;
        this.actual = (Math.pow(upper, 3) / 3) - (Math.pow(lower, 3) / 3);
        evaluateMethod(whichWay);
        System.out.println("Actual value: " + actual);
        System.out.println("Absolute error: " + absoluteError + ", Relative error: " + relativeError + ".");
    }    

    /**
     * Evaluates all calculations
     * @param whichWay, the string to determine left, right, trapezoid method
     */
    private void evaluateMethod(String whichWay) {
        if(whichWay == "l" || whichWay == "L") {
            System.out.println("Using left hand endpoints, on the integral (" + lower + ", " + upper + ") with "
                                + rect + " rectangles.....");
            System.out.println("The approximate value is: " + integrateLeft() + ".");           
        }
        else if(whichWay == "r" || whichWay == "R") {
            System.out.println("Using right hand endpoints, on the integral (" + lower + ", " + upper + ") with "
                                + rect + " rectangles.....");
            System.out.println("The approximate value is: " + integrateRight() + ".");          
        }
        else if(whichWay == "t" || whichWay == "T") {
            System.out.println("Using the trapezoid method, on the integral (" + lower + ", " + upper + ") with "
                                + rect + " rectangles.....");
            System.out.println("The approximate value is: " + integrateTrapezoid() + ".");          
        }
        else {
            throw new IllegalArgumentException("Bad string input. Please restart program");
        }
    }

    /**
     * Left hand endpoint integration
     * @return the approximate value as a double
     */
    private double integrateLeft() {        
        double sum = 0;
        // First interval to the last interval, depending on number of rectangles
        double lowerAlt = lower;
        for(int i = 0; i < rect; i++) {         
            sum += evaluate(lowerAlt);
            lowerAlt = lowerAlt + deltaX;
        }
        absoluteError = Math.abs(actual - (sum * deltaX));
        relativeError = Math.abs(absoluteError / actual);
        // Multiply entire sum by deltaX
        return Math.abs(sum * deltaX);
    }

    /**
     * Right hand endpoint integration
     * @return the approximate value as a double
     */
    private double integrateRight() {
        double sum = 0;
        // First interval to the last interval, depending on number of rectangles
        double lowerAlt = lower + deltaX;
        for(double i = 0; i < rect; i++) {
            sum += evaluate(lowerAlt);
            lowerAlt = lowerAlt + deltaX;
        }
        absoluteError = Math.abs(actual - (sum * deltaX));
        relativeError = Math.abs(absoluteError / actual);
        // Multiply entire sum by deltaX
        return Math.abs(sum * deltaX);
    }

    /**
     * Trapezoid method of integration
     * @return the approximate value as a double
     */
    private double integrateTrapezoid() {
        double sum = 0;
        // first interval after the lower bound, to the last interval before upper bound depending on # of rectangles
        double lowerAlt = lower + deltaX;
        for(int i = 1; i < rect; i++) {
            sum += evaluate(lowerAlt) * 2;
            lowerAlt = lowerAlt + deltaX;
        }
        // Now pass the lower and upper values into the function and add to total sum
        sum += evaluate(lower) + evaluate(upper);
        absoluteError = Math.abs(actual - (sum * (deltaX / 2)));
        relativeError = Math.abs(absoluteError / actual); 
        // Mulitply calculation by deltaX / 2
        return Math.abs(sum * (deltaX / 2));
    }

    /**
     * Method to define the actual function
     * @param x, function input value
     * @return the function output value f(x)
     */
    private double evaluate(double x) {
        //Please enter your desired function here:
        return Math.pow(x, 2);
    }


    /**
     * Main method
     * @param args, the command line arguments
     */
    public static void main(String[] args) {
        String str;
        double a = Double.parseDouble(args[1]);
        double b = Double.parseDouble(args[2]);
        int n = Integer.parseInt(args[3]);
        if(args[0].equals("l") || args[0].equals("L")) {
          new Integrate("l", a, b, n);
        }
        else if(args[0].equals("r") || args[0].equals("R")) {
          new Integrate("r", a, b, n);
        }
        else if(args[0].equals("t") || args[0].equals("T")) {
          new Integrate("t", a, b, n);
        }    
      }
}

Внутри моего метода AssessmentMethod() он проверяет строку, и даже несмотря на то, что аргументы команды передавались в допустимой строковой букве (не char), он не видел ее как строку и выдавал исключение. Спасибо


person Chris Wilson    schedule 24.10.2015    source источник
comment
может быть, это немного поздно, но я не нахожу исключения в вашем вопросе?   -  person A ツ    schedule 25.10.2015
comment
Возможный дубликат Как сравнивать строки в Java?   -  person guido    schedule 25.10.2015
comment
@ᴳᵁᴵᴰᴼ этот сравнивает ввод с равным. ваш дубликат не   -  person A ツ    schedule 25.10.2015
comment
Вы говорите, что new Integrate(args[0], a, b, n); приводит к исключению?   -  person Kayaman    schedule 25.10.2015
comment
@Aツ это происходит в main, но нет в evaluateMethod()   -  person guido    schedule 25.10.2015
comment
@ᴳᵁᴵᴰᴼ ты прав.   -  person A ツ    schedule 25.10.2015


Ответы (2)


В вашем методе оценки() измените whichWay == "l" на whichWay.equals("l"), как в main():

private void evaluateMethod(String whichWay) {
        if(whichWay.equals("l") || whichWay.equals("L")) {
            System.out.println("Using left hand endpoints, on the integral (" + lower + ", " + upper + ") with "
                                + rect + " rectangles.....");
            System.out.println("The approximate value is: " + integrateLeft() + ".");           
        }
        else if(whichWay.equals("r") || whichWay.equals("R")) {
            System.out.println("Using right hand endpoints, on the integral (" + lower + ", " + upper + ") with "
                                + rect + " rectangles.....");
            System.out.println("The approximate value is: " + integrateRight() + ".");          
        }
        else if(whichWay.equals("t") || whichWay.equals("T")) {
            System.out.println("Using the trapezoid method, on the integral (" + lower + ", " + upper + ") with "
                                + rect + " rectangles.....");
            System.out.println("The approximate value is: " + integrateTrapezoid() + ".");          
        }
        else {
            throw new IllegalArgumentException("Bad string input. Please restart program");
        }
    }

Потому что для сравнения значения String вы должны использовать эту функцию. (см. документацию)

== тесты на ссылочное равенство

.equals() проверяет равенство значений

person Simone Pessotto    schedule 24.10.2015
comment
Спасибо всем. глупые маленькие ошибки, подобные этой, которые я хочу предотвратить. Больше нет необходимости в операторах if/else в моем основном методе. Цените помощь. - person Chris Wilson; 25.10.2015

В методе AssessmentMethod() вы используете ==, когда вы должны использовать .equals()

Например

if(whichWay == "l" || whichWay == "L")

должно быть:

if(whichWay.equals("l") || whichWay.equals("L")

замените все ваши сравнения строк на .equals("[Letter]"), и это должно работать.

Интересно, что в NetBeansIDE ваша программа работает нормально. Он просто выдает предупреждение об указанной выше ошибке.

person Subito    schedule 24.10.2015