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

标签 java

这是我正在处理的编程作业。它采用表示一系列交易的单个字符串输入,并在最后打印总 yield /损失。

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

我使用的输入是:

buy 100 share(s) at $20 each;buy 20 share(s) at $24 each;buy 200 share(s) at $36 each;sell 150 share(s) at $30 each;buy 50 share(s) at $25 each;sell 200 share(s) at $35 each;

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 来清理您的解析。他们会让您将输入与正则表达式进行匹配。此外,您可以在正则表达式中放置括号以提取某些部分。因此,在您的示例中,您实际上只关心三件事:操作(买入或卖出)、数量和价格。

这是一个小例子

 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);

关于编写了Java代码但运行后没有预期的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7801061/

相关文章:

java - 由不同类的线程更新的值不会反射(reflect)在 java 中的另一个类中

java - 断开连接后使用 SFTP 下载 InputStream 时 JSch "pipe closed"

java - 使用 Netbeans 在 Java 中的 JPanel 或 JFrame 中放置 map

Java Swing - 从鼠标监听器更改 JComponent 不透明度

java - JSCH - 私钥无效

java - Netflix Zuul - java.lang.ClassNotFoundException : rx. functions.Func1

Java - 由 LDAP 属性组成的正则表达式模式

java - 有 SQLite 查询 validator 库吗?

java - 什么是NullPointerException,我该如何解决?

Javafx 更新对象属性上的 ListCell