현재 제 3 년 프로그래밍 프로젝트와 해당 Folio 추적기를 수행하고 있습니다. :/나는 Stock_API 및 Portfolio_API 인터페이스 (그 중 구현) 상자에 포장하고 인스턴스화 GUI 클래스는 이렇게 두 개의 매개 변수 소요 : 나는에 이러한 인터페이스의 구현을 얻기의 방법으로이 생성자를 사용Java - arraylist에 객체를 추가 한 다음 arraylist에 다른 객체를 추가하면 첫 번째 요소를 덮어 씁니다.
public GUI(Portfolio_API p, Stock s){
tempPort = p;
tempStock = s;
}
을 GUI (이 프로젝트의 주요 목적 중 하나임)에 구현을 노출시키지 않고 GUI. 포트폴리오 객체에는 이름 (문자열)과 ArrayList가 있습니다. 주식 개체에는 시세 기호 (문자열), 주식 이름 (문자열), 공유 값 (부동 소수점), 공유 수 (int) 및 보유 값 (부동 소수점)이 있습니다.
GUI에서 나는 portfolio_API 유형의 객체를 보유하는 portCollection 배열 목록을 가지고 있으며 이것은 시스템이 여러 포트폴리오를 추적 할 수 있도록합니다. 또한 위의 코드 블록에서 언급 한 바와 같이 tempStock 및 tempPort 객체가 있습니다.
유감스럽게도 프로그램에 대한 자세한 내용은 너무 많아요.하지만 전 상황을 파악할 수 있도록 최선을 다했습니다. 어쨌든, 바로 옆에있는 문제. GUI를 사용하여 시세 기호, 주식 이름 및 주식 수를 얻는 방법이 있으며 현재 포트폴리오에 주식을 추가합니다 (각 포트폴리오에는 자체 탭이 있음). 이 방법은 다음과 같습니다.
public void addStock() {
int num_shares = 0;
float dailyChange = 0.0f;
float stockValue = 0.0f;
boolean succeed = true;
// GUI gets information of stock from user
String ticker = JOptionPane.showInputDialog(frame,
"Enter the ticker symbol:");
String stockName = JOptionPane.showInputDialog(frame,
"Enter the Stock name:");
try {
num_shares = Integer.parseInt(JOptionPane.showInputDialog(frame,
"Enter the number of shares:"));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame,
"Number of shares was not an integer. Try again");
succeed = false;
}
// If parsing was successful...
if (succeed) {
tempStock.setTicker(ticker);
tempStock.setNumberOfShares(num_shares);
tempStock.setStockName(stockName);
// Fetches newest value using the current ticker symbol
boolean succeedUpdate = tempStock.updateShareValue();
if (succeedUpdate) {
tempStock.calculateValueOfHolding();
// Adds to the current portfolio...
String tabName = tabbedPane.getTitleAt(tabbedPane
.getSelectedIndex());
System.out.println(tabName);
findPortfolio(tabName).addStock(tempStock);
findPortfolio(tabName).sort();
// ...Then adds it to the table
JPanel j = (JPanel) tabbedPane.getSelectedComponent()
.getComponentAt(0, 0);
JViewport v = ((JScrollPane) j.getComponent(0)).getViewport();
JTable table = (JTable) v.getComponent(0);
float currentTotal = findPortfolio(tabName).getTotal();
// Updates the total label
((JLabel) j.getComponent(1)).setText("Total: " + currentTotal);
Object[] newStock = { tempStock.getTicker(),
tempStock.getStockName(),
tempStock.getNumberOfShares(),
tempStock.getShareValue(),
tempStock.getValueOfHolding() };
((DefaultTableModel) table.getModel()).addRow(newStock);
}
}
}
재고를 두 개 이상 추가하면 새 재고가 이전 재고를 대신 사용하여 효과적으로 덮어 씁니다. 나는 그것을하고있는 tempStock의 재사용이라고 생각한다. 확신 할 수는 없겠지만 확실하게 변수를 arraylist에 추가하면 해당 arraylist의 일부가되며 tempStock 변수와 연관이 필요하지 않습니다. 언급 arraylists와 함께 사용
방법 :
private Portfolio_API findPortfolio(String name) {
Portfolio_API p = null;
for (int i = 0; i < portCollection.size(); i++) {
if (portCollection.get(i).getName() == name) {
p = portCollection.get(i);
}
}
은이 두 가지가 포트폴리오 클래스에 있습니다
@Override
public boolean addStock(Stock_API s) {
if (!doesExist(s)) {
portfolio.add(s);
return true;
} else {
return false;
}
}
@Override
public boolean doesExist(Stock_API s) {
boolean found = false;
for (int i = 0; i < portfolio.size(); i++) {
if (portfolio.get(i).getTicker() == s.getTicker()) {
found = true;
}
}
return found;
}
I했습니다 단지 내가 벽돌 벽에 부딪 때문에 도움을 여기에 온다 나는 정말로 도움이 필요하다. 누구든지 내게 어떤 제안을 줄 수 있다면, 나는 영원히 당신의 빚을지게 될 것입니다.
덕분에, 크리스
'ArrayList'를 사용하는 코드를 표시하지 않았으므로이 코드를 고정하기가 어렵습니다. –
아, 죄송합니다. 게시물을 편집하고 arraylist를 사용하는 몇 가지 방법을 추가합니다. – ChrisMacDee
개체를 목록에 "추가"할 때 해당 개체의 복사본이 아니라 해당 개체에 대한 참조를 추가합니다. 나중에 개체를 변경하면 해당 개체에 대한 모든 참조에서 해당 변경 사항을 볼 수 있습니다. –