在这个程序中,我想输入虚假股票并用股票代码搜索它们,并打印最后买入的250只股票的平均成本。这是我到目前为止的地方,每当我输入2时,程序崩溃而没有任何错误消息。
package stocks;
import java.util.*;
public class Stocks {
private String sym;
private List<Purchase> purchases;
public Stocks(final String symbol) {
this.sym = symbol;
purchases = new ArrayList<Purchase>();
}
public void addPurchase(final int amt, final double cost) {
purchases.add(new Purchase(amt, cost));
}
public String getSym() {
return sym;
}
public void setSym() {
this.sym = sym;
}
public double getAvg250() {
int i = 0;
int total = 0;
int shares = 0;
while (i < purchases.size()) {
Purchase p = purchases.get(i);
if (shares + p.getAmt() >= 250) {
total += (250 - shares) * p.getCost();
shares = 250;
break;
}
shares += p.getAmt();
i++;
}
return total * 1.0 / shares;
}
public class Purchase {
private int amt;
private int cost;
public Purchase(int amt, double cost) {
}
public int getAmt() {
return amt;
}
public void setAmt(int amt) {
this.amt = amt;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
}
public static void main(String[] args) {
int choice = 0;
ArrayList<Stocks> StocksList = new ArrayList<Stocks>();
Map<String, Stocks> stocks = new HashMap<String, Stocks>();
while (choice == 0) {
System.out.println("Enter 1 to input a new stock, or 2 to query a stock's price, 3 to quit: ");
Scanner sc1 = new Scanner(System.in);
choice = sc1.nextInt();
if (choice == 1) {
Scanner sc2 = new Scanner(System.in);
System.out.println("Please enter the stock symbol: ");
String sym = sc2.next();
System.out.println("Please enter the number of shares: ");
int amt = sc2.nextInt();
System.out.println("Please enter the price per share: ");
double cost = sc2.nextDouble();
Stocks s = stocks.get(sym);
if (s == null) {
s = new Stocks(sym);
stocks.put(sym, s);
}
s.addPurchase(amt, cost);
choice = 0;
if (choice == 2) {
Scanner sc3 = new Scanner(System.in);
System.out.println("Please enter the symbol of the stock you wish to see: ");
String search = sc3.next();
if (stocks.containsKey(search)) {
System.out.println(search + "'s LIFO price is " + s.getAvg250());
choice = 0;
}
}
if (choice == 3) {
}
}
}
}
}
答案 0 :(得分:0)
您检查用户是否输入了&#34; 2&#34;在if块中检查用户是否输入&#34; 1&#34;。而且因为if (choice == 1)
阻止你的程序离开while循环后选择仍然是2。
应该是这样的(如果你保持这种编程风格)
while (choice == 0) {
// ...
if (choice == 1) {
}
if (choice == 2) {
}
if (choice == 3) {
break;
}
// ...
choice = 0
}
而不是
while (choice == 0) {
// ...
if (choice == 1) {
choice = 0;
// choice 2 will never be true
if (choice == 2) {
}
}
}