פורסם 2007 בספטמבר 1518 שנים לכתוב תכנית שמנהלת מכירות ממחסן פריטיםמחסן מיוצג כמערך דו ממדי בו 100 שורות ו- 2 עמודות. קוד פריט הוא אינדקס של שורה.עמודות: כמות במלאי ומחיר.פעולות:1. קניית מוצר:הקלט הוא: קוד פריט וכמות לקנייההפלט הוא : סכום לתשלום. יש לעדכן מלאי בהתאם2. סכום פריטים:פלט סכום שווי כספי של כל המלאיליצור 5 תהליכונים שמייצגים 5 לקוחות שיכולים לבצע אחת משתי הפעולות ולהציג תוצאה של כל פעולה בהתאם.הנה מה שניסיתי לעשות.זה כמעט עובד אבל הקניה לא מצליחה.[left]public class Main{ public static void main(String[] args) { Mahsan b = new Mahsan(); int i; for (i = 0; i < 5; i++) { BuyRunnable r = new BuyRunnable(b); Thread t = new Thread(r); t.start(); } }}class Mahsan{ /** Constructs the mahsan. @param n the number of accounts @param initialBalance the initial balance for each account */ public Mahsan() { storage = new int [2][100]; for(int i=0;i<100;++i) { storage[0][i]=(int) (Math.random()*100); storage[1][i]=(int)(Math.random()*100); } } /** Transfers money from one account to another. @param from the account to transfer from @param to the account to transfer to @param amount the amount to transfer */ public synchronized void buy(int from, int amount) throws InterruptedException { if (storage[0][from]>amount) { System.out.print(Thread.currentThread()); storage[0][from] -= amount; System.out.printf(" Bought %d code %d iteams for %d $",amount,from,amount*storage[1][from]); System.out.printf(" Total Balance: %d%n", getTotalBalance()); } } /** Gets the sum of all account balances. @return the total balance */ public synchronized int getTotalBalance() { int sum = 0; for (int i=0;i<100;++i) sum += storage[0][i]*storage[1][i]; return sum; } private final int[][] storage;}class BuyRunnable implements Runnable{ /** Constructs a transfer runnable. @param b the bank between whose account money is transferred @param from the account to transfer money from @param max the maximum amount of money in each transfer */ public BuyRunnable(Mahsan b) { mahsan = b; } public void run() { try { while (true) { int amount =(int) Math.random()*100; fromAccount =(int) Math.random()*100; mahsan.buy(fromAccount, amount); Thread.sleep((int) (DELAY * Math.random())); } } catch (InterruptedException e) {} } private Mahsan mahsan; private int fromAccount; private int repetitions; private int DELAY = 1000;}[/left]
פורסם 2007 בספטמבר 1618 שנים קודם כל, נראה לי שהתבלבלת בין השורות והעמודות - זה צריך להיות ככה (לא שזה ממש משנה):storage = new int[100][2];(בד"כ מתייחסים לאינדקס הראשון כשורה ולשני כעמודה)דבר שני, תבדוק אם לא עף ה-exception (מה החוכמה לתפוס exception ולא לעשות איתו כלום?)דבר שלישי, שים לב שאתה מגדיר את r ו-t בתור הלולאה, כך שהם נזרקים לפח אחרי סוף הלולאה (כי הם כבר לא ב-scope). אתה צריך לדאוג שהם ימשיכו להתקיים גם מחוץ ללולאה.
ארכיון
דיון זה הועבר לארכיון ולא ניתן להוסיף בו תגובות חדשות.