-1

I have created a single-class Java game in which we need to buy and sell stocks, I have just started Java and am a newbie so need help + this code is not very good.

import java.io.*;
import java.util.Random;
public class stock_holding_game
{
    static Random randomn = new Random();
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 public static void main(String[] args)throws IOException
  {
        double cash = 30.0;
        double stocks[] = {0,10,20,40,80,160,320,640};//cost of stocks (there are 7 stocks each with different price)
        int mystocks[] = {0,0,0,0,0,0,0,0};
        pass("Enter your name");
        String name = br.readLine();
        pass("Hi "+name);
        commandlist();
        boolean booleancheck = true;
        while(booleancheck)
        {
            pass("Please enter your command");
            String command = br.readLine();
            command =" "+command+"  ";
            char c = command.charAt(2);
            switch(c)
            {
                case'h':
                pass("enter the stock ID number");
                int s1 = Integer.parseInt(br.readLine());
                if(s1>0&&s1<=8)
                {
                    pass("Starting price: "+stocks[s1]);                    
                    double t = randomn.nextDouble() *(stocks[s1]/10.0);
                    int add = randomn.nextInt(2);
                    if(add==0)stocks[s1]=stocks[s1]+t;
                    else
                    stocks[s1]=stocks[s1]-t;
                    pass("Current price: "+stocks[s1]);
                }
                else
                {
                    pass("Wrong Number");
                    pass("Enter a number from 1 to 8");
                    pass("Do whole task again xD");
                }
                break;
                case 'n':
                pass("Enter the stock ID number");
                int s2 = Integer.parseInt(br.readLine());
                if(s2>0&&s2<=8)
                {
                    double t = randomn.nextDouble() *(stocks[s2]/10.0);
                    int add = randomn.nextInt(2);
                    if(add==0)stocks[s2]=stocks[s2]+t;
                    else
                    stocks[s2]=stocks[s2]-t;
                    pass("Current price: "+stocks[s2]);
                    pass("You currently have: "+mystocks[s2]+ " of these stocks");
                    pass("You have " +cash+" cash");
                    pass("Enter the number of stocks you wish to buy");
                    int nsbuy = Integer.parseInt(br.readLine());
                    if(nsbuy<0)pass("Idiot ! , add atleast 1 if you wish to buy");
                    else if(nsbuy==0);
                    else
                    {
                        double checkprice = nsbuy*stocks[s2];
                        if(checkprice > cash)
                        {
                            pass("You don't have enough cash in hand !");
                        }
                        else
                        {
                            cash = cash - checkprice;
                            mystocks[s2] = mystocks[s2] + nsbuy;
                            pass("Now you have "+mystocks[s2]+ " of stock ID " +s2);
                            pass("You are left with "+cash);
                        }
                    }
            }   
            else
            {
                pass("Invalid Input!");
                pass("Enter a number from 1 to 8");
            }
            break;
            case 'a':
            pass("You have currentln " +cash+" cash");
            break;
            case 'x':
            booleancheck = false ; 
            pass("You leave with "+cash+" cash");
            pass("Bye, Hope to see you again .");
            break;
            case 'o':
            commandlist();
            break;
            case 'y':
            for(int xyz = 1; xyz<mystocks.length - 1;xyz++)
            {
                pass("You have "+mystocks[xyz]+ " of stock ID "+xyz);
            }
            break;
            case 'e':
            pass("Enter the stock ID number");
            int s3 = Integer.parseInt(br.readLine());
            if(s3>0&&s3<=8)
            {
                double t = randomn.nextDouble() *(stocks[s3]/10.0);
                int add = randomn.nextInt(2);
                if(add==0)stocks[s3]=stocks[s3]+t;
                else
                stocks[s3]=stocks[s3]-t;
                pass("Current price: "+stocks[s3]);
                pass("You currently have: "+mystocks[s3]+ " of these stocks");
                pass("You have " +cash+" cash");
                pass("Enter the number of stocks you wish to sell");
                int nssell = Integer.parseInt(br.readLine());
                if(nssell<0)pass("Enter atleast 1 if you wish to sell(in case you have)");
                else if(nssell==0);
                else
                {
                    double nscheckprice = stocks[s3]*nssell;
                    if(nssell>mystocks[s3])pass("You don't jave that many stocks !");
                    else
                    mystocks[s3] = mystocks[s3] - nssell;
                    cash = cash + nscheckprice;
                    pass("You have successfully sold your " +nssell+" stocks for "+nscheckprice);
                    pass("Now , you have , "+ mystocks[s3]+ " of stock ID "+s3);
                    pass("You are left with " +cash + " cash");
                }
            }
            else
            {
                pass("Invalid Input!");
                pass("Enter a number from 1 to 8");
            }
            break;
            default:
            pass("Invalid Input!");
            break;                
        }
    }
}
private static void commandlist()
{
    pas("Your command list : ");
    pas("checkstock - check the current and earlier value of a stock");
    pas("invest - buy shares ");
    pas("sell - sell ur share ");
    pas("exit - leave the game");
    pas("my - show ur all current stock");
    pas("cash - show ur current cash in hand");
    pas("There are 7 stock with id 1 , 2 , 3 , and so on till 7")
    pas("Remember ! It is case sensitive");
}
private static void pass(String source)
{
    System.out.println(source);
}
private static void pas(String source)
{
    System.err.println(source);
}
}

I wish to have an applet for this code but I don't know much about applets. I wish to use some buttons instead of typing. I know codes to add buttons but don't know how to use them. Need help on it, all replies would be appreciated.

And yes , also tell how is this game (rate this game), but rate as if a newbie as made it. Now, instead of going on full ask on how to convert it into an applet I wish to ask it in small blocks. First of all how shall I use a button and tell my PC how to proceed?

This is my code:

import java.awt.*;

public class Buttonsuse extends java.applet.Applet
{
    Button invest , sell , check ;
    public void init()
    {
        setBackground (Color.white);
        setLayout(new FlowLayout (FlowLayout.CENTER,10,10));
        invest = new Button("Invest");
        sell = new Button("Sell");
        check = new Button("Check");
        add(invest);
        add(sell);
        add(check);
      }
}

Now, how shall I know and tell the computer that a button is pressed, like if user presses invest button, it prints "you wish to invest".

How shall I do that?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Darsh
  • 27
  • 8
  • Take a look at [Swing Tutorial](http://docs.oracle.com/javase/tutorial/uiswing/) then have a look at [Applets tutorial](http://docs.oracle.com/javase/tutorial/deployment/applet/index.html) – Paul Samsotha Jan 14 '14 at 07:42
  • *"Need help on converting a java game to a java applet"* Noooooooo! Convert it to a `JFrame` then launch it from a link using [Java Web Start](http://stackoverflow.com/tags/java-web-start/info). It will be quicker to get to the point of deployment, lower maintenance, and the users will thank you. – Andrew Thompson Jan 14 '14 at 09:01
  • `public class Buttonsuse extends java.applet.Applet` And no matter what way you decide to proceed, use Swing components rather than AWT. See my answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. – Andrew Thompson Jan 14 '14 at 09:07
  • ok i will surely read it on swing but actually i will have to start from beginning in swing , but in awt i have already started , thanz by the way. – Darsh Jan 14 '14 at 10:13

1 Answers1

2

Your current program is little more than a large static main method with a few small supporting static methods. Since this code is very linear, as most console programs are, and since it has no OOP-compliant classes, there is no way to directly convert or re-use any of this code to use in an event-driven GUI. I suggest:

  • Extract out the logic or brains behind your program into true OOP classes with instance fields, constructors and non-static methods.
  • Only after doing this should you consider creating a GUI to display the logic.
  • Read a decent book on OOP and Java such as "Thinking in Java" as this will help you think and code in an OOP way.

Non-GUI Classes to consider:

  • Stock classes with String name, double (or BigDecimal) value, String abbreviated name
  • Player that holds a String for name, a HashMap<Stock, Integer> for Stocks held and number of shares.
  • Market where a player can buy and sell Stocks.

The bottom line is that there is no one single simple way to "convert" this code to a GUI, and instead you should focus on learning Java fundamentals, and experiment with your code while learning (for that's how you learn).

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373