编写的Java代码,但运行后没有预期的输出

时间:2011-10-18 00:10:06

标签: java

这是我正在进行的编程工作。它需要一个字符串输入来表示一系列事务并最终打印出总收益/损失。

我已经编写了代码并且认为它应该做我想要的...但是没有。使用指定的输入运行程序后,我没有得到任何输出。

我正在使用的输入是:

  

以每股20美元的价格购买100股;以每股24美元的价格购买20股;购买200股   每股36美元的股票;每股30美元卖出150股;买入50股   每个25美元;每个35美元卖出200股;

import java.util.*;
import java.text.*;

public class Stocks {

private int shares;
private int price;
private int temp;
private static int total;
private int finalPrice;
private int finalShares;
private Queue<Stocks> StockList = new LinkedList<Stocks>();

private static NumberFormat nf = NumberFormat.getCurrencyInstance();

public Stocks()
{
    shares      = 0;
    price       = 0;

}

public Stocks(int shares, int price)
{
    this.shares     = shares;
    this.price      = price;
}

public int getShares()
{
    return this.shares;
}

public int getPrice()
{
    return this.price;
}

public void setShares(int shares)
{
    this.shares = shares;
}

public void setPrice(int price)
{
    this.price = price;
}

public void sell() {
    int sharesToSell = this.getShares();
    int priceToSell = this.getPrice();

    while (!StockList.isEmpty()) {

         int numShares = StockList.peek().getShares();
         int sharePrice = StockList.peek().getPrice();

        if (numShares < sharesToSell || numShares == sharesToSell) {
            temp = sharesToSell - numShares; // remaining shares to sell
            finalShares = sharesToSell - temp; // # shares selling at price
            finalPrice = priceToSell - sharePrice; // shares sold at adjusted price
            total += (finalPrice * finalShares); // Calculates total price
            StockList.remove();
            sharesToSell = temp; // Remaining shares needed to be sold @ price
        }

        if (numShares > sharesToSell) {
            temp = numShares - sharesToSell; // Remaining shares that were bought
            finalPrice = priceToSell - sharePrice; // Shares sold at adjusted price
            total += (finalPrice * sharesToSell); // adds to running total
            StockList.peek().setShares(temp);
        }
    }
}

public void buy() { 
    int numShares = this.getShares();
    int priceToBuy = this.getPrice();

    Stocks newStock = new Stocks(numShares,priceToBuy);
    StockList.add(newStock); // adds stock to list

    int temptotal = (numShares * priceToBuy); // decreases running total
    total += (-1 * temptotal);
}

public static int getTotal() { // gets total profit (or loss)
    return total;
}

// *****MAIN METHOD*****
public static void main(String[] args){


    Scanner scan = new Scanner(System.in);

    System.out.println("Enter transaction sequence:");

    String input = scan.nextLine().trim();
    String[] inputArray = new String[50];
    String[] inputArray2 = new String[50];
    int numShares, sharePrice;

    inputArray = input.split(";");

    for (String i : inputArray) {
        if (i.toUpperCase().contains("BUY")) {
            inputArray2 = i.split(" ");
            inputArray2[4] = inputArray2[4].substring(1);

            try {
                numShares = Integer.parseInt(inputArray2[1]);
                sharePrice = Integer.parseInt(inputArray2[4]);

                Stocks newStock = new Stocks(numShares,sharePrice);
                newStock.buy();

            } catch (NumberFormatException e) {
                System.out.println("Error");
                return;
            }

        }

        else if (i.toUpperCase().contains("SELL")) {
            inputArray2 = input.split(" ");
            inputArray2[4] = inputArray2[4].substring(1);

            try {
                numShares = Integer.parseInt(inputArray2[1]);
                sharePrice = Integer.parseInt(inputArray2[4]);

                Stocks newStock = new Stocks(numShares,sharePrice);
                newStock.sell();

            } catch (NumberFormatException e) {
                System.out.println("Error");
                return;
            }
        } else {
            System.out.println("Error - input does not contain buy/sell");
        }
    } System.out.println(nf.format(getTotal()));
}

}

2 个答案:

答案 0 :(得分:2)

通过查看java.util.regex.Matcher和java.util.regex.Pattern,您可以大量清理解析。它们可以让您将输入与正则表达式进行匹配。此外,您可以将parens放在正则表达式中以提取某些部分。所以在你的例子中,你真的只关心三件事:操作(买入或卖出),数量和价格。

这是一个小例子

 String sentence = "john programs 10 times a day";

 // here's our regex - each set of parens is a "group"
 Pattern pattern = Pattern.compile("([A-Za-z]+) programs ([0-9]+) times a day");
 Matcher matcher = pattern.matcher(sentence);

 String person = matcher.group(1); // here we get the first group
 String number = Integers.parseInt(matcher.group(2)); // here we get the second group

 System.out.println("Person: " + person + " Number: " + number);

答案 1 :(得分:1)

在解析买入交易时,似乎方法会立即返回。您可能打算将 return 语句放在 catch 块中。