【问题标题】:Java code written but no expected output after running编写 Java 代码但运行后没有预期输出
【发布时间】:2011-10-18 09:50:21
【问题描述】:

这是我正在处理的一项编程任务。它需要一个代表一系列交易的字符串输入,并在最后打印总收益/损失。

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

我使用的输入是:

以每股 20 美元的价格购买 100 股;以每股 24 美元的价格购买 20 股;购买 200 每股 36 美元;以每股 30 美元卖出 150 股;以每股 30 美元买入 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()));
}

}

【问题讨论】:

  • 请添加作业标签。
  • 你能指定在哪一行输入吗?
  • 您是否有直觉认为哪里出了问题?
  • 您真的要在 SELL 代码中执行 `System.out.println(getTotal());` 吗?我想你会想在最后这样做。
  • @alf 在 main 方法中的 scan.nextLine 处输入。

标签: java


【解决方案1】:

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

【讨论】:

  • 我得试试这个。谢谢!
【解决方案2】:

看起来 ma​​in 方法在解析 BUY 交易时立即返回。您可能打算将 return 语句放在 catch 块中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    相关资源
    最近更新 更多