0

私は証券取引所タイプのプログラムを作成していますが、これまでのところ、ユーザーからのコマンドを適切に受け取るように入力が機能しています。ただし、入力に対して行うことは期待どおりに機能しません。最初に混乱したのは、コードを実行すると NullPointerException がスローされる理由です。

基本的に、プログラムは 3 つの入力を受け取り、その後にそれらの間に空白が続きます。たとえば、1 株あたり 20 ドルで 30 株を購入したい場合は、次のように入力します。

ロ 30 20

次に、それを 3 つの部分に分割し、配列に格納します。その後、配列の最初のインデックスを比較して、プログラムが何をすべきかを確認します。この例では購入するため、buy メソッドを呼び出して、シェアの金額とシェアの値を私の CircularArrayQueue に保存します。

Node に格納された共有値と共有量を取得しますが、CirularArrayQueue で enqueue メソッドを呼び出して Node を Queue に保存しようとすると、NullPointerException が発生します。

私が遭遇したもう 1 つの問題は、プログラムの終了です。プログラムは、入力の最初のインデックス値が "q" であることを確認したときに終了することになっています。ブール値の quit が false の場合にループすることを示す while ループを作成しました。次に、while ループ内で、stockParts[0] の値が「q」であるかどうかを確認する if ステートメントをチェックしました。その場合、quit の値を true に変更してループを終了できるようにしますが、何らかの理由で終了せず、まだループしています。

私はこれらの問題について数時間頭を悩ませてきましたが、問題の根本を見つけることができないようです. 誰かがこれについて私を助けてくれますか? 以下は、メイン クラスと CircularArrayQueue クラスのコードです。

import java.util.Scanner;
import java.lang.Integer;

public class StockTran {
String command = "";
String[] stockParts = null;
CircleArrayQueue Q;
boolean quit = false;

public StockTran(String inputCommand) {
    try {
        Scanner conReader = new Scanner(System.in);
        this.command = inputCommand.toLowerCase();
        this.stockParts = command.split("\\s"); // splits the input into three parts

        buyShares(Integer.parseInt(stockParts[1]), Integer.parseInt(stockParts[2]));        //testing purpose only

        while (quit == false) {
            if (this.stockParts[0] == "q") {        // ends transaction and terminates program
                System.out.println("Share trading successfully cancelled.");
                quit = true;    
            }

            if (this.stockParts == null || this.stockParts.length > 3) {
                throw new Exception("Bad input.");
            }

            if (stockParts[0] == "b") {     // checks to see if it is a buying of shares
                int shares = Integer.parseInt(stockParts[1]);       // stores share amount
                int value = Integer.parseInt(stockParts[2]);        // stores selling value
                buyShares(shares, value);       // calls buyShares method and adds share to queue
            }
            else if (stockParts[0] == "s") {        // checks to see if it is a selling of shares
                int shares = Integer.parseInt(stockParts[1]);       // stores share amount
                int value = Integer.parseInt(stockParts[2]);        // stores selling value
                sellShares(shares, value);      // calls sellShares method
            }
            else if (stockParts[0] == "c") {        // checks to see if it is capital gain
                capitalGain();      // calls capitalGain and calculates net gain
            }
            System.out.println("Enter your next command or press 'q' to quit: ");
            command = conReader.nextLine().toLowerCase();
            stockParts = command.split("\\s");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}


public void buyShares(int shareAmout, int shareValue) {     // takes in share total and values for each share
    Node temp = new Node(shareAmout, shareValue);       // stores values into node
    try {
        Q.enqueue(temp);        // enqueues the node into the CircularArrayQueue
        //System.out.println(Q.toString());

    } catch (FullQueueException e) {
        e.printStackTrace();
    }

}

public void sellShares(int shareAmount, int sharePrice) {   // ToDo

}

public int capitalGain() {  // ToDo
    return 0;
}

public static void main(String[] args) {
    String inputCommand = "";
    Scanner mainReader = new Scanner(System.in);

    System.out.println("Enter 'b' to purchase share, 's' to sell share, 'c' for capital gain, or 'Q' to quit: ");
    inputCommand = mainReader.nextLine();

    StockTran tran = new StockTran(inputCommand);
}
}
public class CircleArrayQueue implements Queue {
protected Node Q[];     // initializes an empty array for any element type
private int MAX_CAP = 0;        // initializes the value for the maximum array capacity
private int f, r;

public CircleArrayQueue(int maxCap) {
    MAX_CAP = maxCap;
    Q = new Node[MAX_CAP];  // sets Q to be a specific maximum size specified
    f = 0;      // sets front value to be 0
    r = 0;      // sets rear value to be 0;
}

public int size() {
    return (MAX_CAP - f + r) % MAX_CAP;     // returns the size of the CircularArrayQueue
}

public boolean isEmpty() {      // if front and rear are of equal value, Queue is empty
    return f == r;
}

public Node front() throws EmptyQueueException {        // method to get the front value of the CircularArrayQueue
    if (isEmpty()) throw new EmptyQueueException("Queue is empty.");
        return Q[f];        // returns object at front of CircularArrayQueue
}

public Node dequeue() throws EmptyQueueException {  // method to remove from the front of the CircularArrayQueue
    if (isEmpty()) throw new EmptyQueueException("Queue is empty.");
        Node temp = Q[f];       // stores front object in local variable
        Q[f] = null;        // sets the value to be null in the array
        f = (f + 1) % MAX_CAP;      // sets the new front value to be this
        return temp;        // returns the object that was originally in the front
}

public void enqueue(Node element) throws FullQueueException {       // method to add to the end of the CircualarArrayQueue
    if (size() == MAX_CAP - 1) throw new FullQueueException("Queue has reached maximum capacity.");
        Q[r] = element;     // stores the new element at the rear of array
        r = (r + 1) % MAX_CAP;      // sets the new rear value to be the location after element insertion
}
}
4

2 に答える 2

2

参照 Q を初期化していません。これはフィールド変数であるため、デフォルトで null に初期化されます。

    CircleArrayQueue Q;

このような問題に直面した場合は、デバッグする必要があります。情報源の 1 つは、例外からのスタック トレースです。これにより、例外がスローされた場所がわかります。開発環境のデバッガーに、例外がスローされた時点で自動的に停止するように依頼することもできます。

次に、Java で文字列を比較するときは、== 演算子ではなく equals() メソッドを使用します。equals() メソッドは、オブジェクトの値を比較します。== 演算子は、オブジェクトを指す参照の値を比較します。異なる参照値を持つ 2 つの等しいオブジェクトを持つことができます。

于 2012-09-23T13:15:02.797 に答える
0

CircleArrayQueue Q を初期化します。初期化しない場合。デフォルト値として null を取ります。

CircleArrayQueue q= new CircleArrayQueue(size);
于 2012-09-23T13:17:58.670 に答える