2012-09-23 3 views
0

증권 거래소 유형의 프로그램을 작성하고 있으며 지금까지 사용자로부터 명령을 제대로 받아 들일 수 있도록 입력을 처리했습니다. 그러나 입력 내용이 예상대로 작동하지 않습니다. 내가 혼란스러워하는 첫 번째 이유는 코드를 실행할 때 NullPointerException을 던지는 이유입니다.NullPointerException이 throw되고 프로그램이 예상대로 종료되지 않습니다.

기본적으로 프로그램은 3 가지 입력과 그 사이의 공백을 입력합니다.

B (30) (20)

그것은 다음 3 개 부분으로 나눌 것이며 배열로 저장 : 예를 들어 나는 $ 20 각 30 주식을 사고 싶은 그래서, 나는 다음과 같이 입력을 입력합니다. 그런 다음 배열의 첫 번째 인덱스를 비교하여 프로그램에서 수행해야하는 작업을 확인합니다.이 예제에서는 구매 방법을 호출하고 공유 금액 및 공유 값을 내 CircularArrayQueue에 저장합니다.

노드에 저장된 공유 값과 공유량을 얻지 만 CirularArrayQueue와 함께 대기열에 대기열에 대기열을 저장하는 대기열에 넣기 메소드를 호출하려고하면 NullPointerException이 발생합니다.

내가 겪어 본 또 다른 문제는 프로그램 종료입니다. 이 프로그램은 입력의 첫 번째 인덱스 값이 "q"라는 것을 알면 종료됩니다. boolean quit이 false 일 때 while 루프가 반복된다는 while 루프를 만들었습니다. 그런 다음 while 루프 내에서 stockParts [0]의 값이 "q"인지 확인하는 if 문을 만들었습니다. 그렇다면 종료 값을 true로 변경하여 루프를 종료 할 수 있지만 어떤 이유로 종료 중이 아니며 계속 반복 중입니다.

나는 몇 시간 동안이 문제에 대한 내 머리를 긁어 왔지만 문제의 근원을 찾을 수없는 것 같습니다. 누군가 이걸 도와 주시겠습니까? 그것을 NULL로 기본적으로 초기화있어, 필드 변수입니다 때문에 당신은 참조 Q.를 초기화하지 않은

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 
} 
} 

답변

2

: 내 메인 클래스의 코드와 CircularArrayQueue 클래스입니다 다음.

CircleArrayQueue Q; 

이와 같은 문제가 발생하면 디버깅해야합니다. 정보 소스 중 하나는 예외의 스택 추적입니다.이 추적은 예외가 발생한 곳을 알려줍니다. 예외가 발생하는 지점에서 자동으로 중지되도록 개발 환경의 디버거에 요청할 수도 있습니다.

둘째, Java에서 문자열을 비교할 때 == 연산자 대신 equals() 메서드를 사용하십시오. equals() 메서드는 객체 값을 비교합니다. == 연산자는 객체를 가리키는 참조 값을 비교합니다. 다른 참조 값을 가진 두 개의 동일한 객체를 가질 수 있습니다.

+0

오케이. 도움을 주셔서 감사합니다! 이제 막 프로그램이 종료되지 않는 이유를 알아야합니다 ... – Asdeev

+0

@MohamedBhura 'if (this.stockParts [0] == "q")'는 true를 반환하지 않기 때문에. '=='대신에'equals()'를 사용하면 그것을 고쳐야합니다. –

+0

프로그램 종료의 경우 먼저 문자열 비교 문제를 수정하십시오. (BTW, StackOverflow에 오신 것을 환영합니다. 가장 좋은 대답이라고 생각하시면 왼쪽의 작은 체크 박스를 클릭하십시오.) –

0

초기화하지 않으면 CircleArrayQueue Q를 초기화하십시오. 기본값으로 null을 취합니다.

CircleArrayQueue q= new CircleArrayQueue(size);