簡體   English   中英

編寫的Java代碼,但運行后沒有預期的輸出

[英]Java code written but no expected output after running

這是我正在從事的編程工作。 它需要一個字符串輸入來表示一系列事務並最終打印總增益/損失。

我已經編寫了代碼,並認為它應該可以實現我想要的功能……但是沒有。 使用指定的輸入運行程序后,我沒有得到任何輸出。

我正在使用的輸入是:

以每股20美元的價格購買100股;以每股24美元的價格購買20股;以每股36美元的價格購買200股;以每股30美元的價格賣出150股;以每股25美元的價格購買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()));
}

}

您可以通過查看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);

看起來方法在解析BUY事務時立即返回。 您可能打算將return語句放入catch塊中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM