Display bill total, Java public void display() error - java

I'm having some trouble executing the total bill display. I asked my professor who gave me this small block of code, which I modified to meet my needs, but for some reason it is not executing and has the error:
Illegal start to expression for line --> public void display().
The compiler also suggests to end with a semi colon which I don't believe is accurate.
What am I missing that public void display() is not being executed and is erroneous?
import java.util.Scanner;
public class CoffeeShop
{
/* Author:
Date:
Program: Create a Coffee Shop application that uses a while loop to build a customer order. The Coffee Shops sells coffee ($3.25), espresso ($4.25), and tea ($2.75). The coffee selection presents the customer with the choices of iced (no charge), cream (50 cents), and sugar (50 cents). The espresso selection presents the customer with choice of caramel (no charge) and chocolate (no charge) with one shot (no charge) or two shots ($1.25) of espresso. Once the customer is done, he or she will receive a bill of the total price. After each selection, the customer will have the choice of returning to the main menu for additional purchases. Use nested loops to handle customers' submenu selections.
*/
public static void main(String[] args)
{
//declarations
double coff = 3.25;
double esp = 4.25;
double tea = 2.75;
double cream = .50;
double sugar = .50;
double dblShot = 1.25;
int dblshotQty = 0;
int userInput = 0;
int userInput2 = 0;
int coffQty = 0;
int espQty = 0;
int teaQty = 0;
int creamQty = 0;
int sugarQty = 0;
double runTotal = 0;
double totalCoff = 0;
double totalEsp = 0;
double totalTea = 0;
double totalBill = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Would you like to place an order? press 1 for yes or 2 for no :");
//start a loop with a control variable asking if they would like a cup of coffee yes or no
userInput = scan.nextInt();
while(userInput == 1)
{
System.out.print("Enter 1 for Coffee, 2 for Espresso, or 3 for tea: ");
userInput2 = scan.nextInt();
switch(userInput2)
//if 1 is pressed coffee is ordered
{ // open switch
case '1':
{
coffQty = coffQty + 1;
System.out.print("Press 1 if you would like your coffee iced or 2 for no: ");
userInput = scan.nextInt();
}
{
System.out.print("Press 1 if you would like cream for $.50 or 2 for no: ");
userInput = scan.nextInt();
if ( userInput == 1 )
{
creamQty = creamQty + 1;
}
}
{
System.out.print("Press 1 if you would like sugar for $.50 or 2 for no: ");
userInput = scan.nextInt();
if ( userInput == 1 )
{
sugarQty = sugarQty + 1;
}
}//end case 1
break;
// espresso is ordered ask for double shot
case '2':
{
espQty = espQty +1;
System.out.println("Press 1 for a double shot for $1.25 or 2 for no: ");
userInput = scan.nextInt();
if(userInput == 1)
{
dblshotQty = dblshotQty +1;
}
}//end case 2
break;
//tea is ordered
case '3':
{
teaQty = teaQty + 1;
System.out.println("You have selected tea! Great Choice.");
}//end case 3
}//end switch
// create output display for total bill adding all totals
public void display()
{
double totalCoff = coffQty * coff + cream * creamQty + sugar * sugarQty;
double totalEsp = espQty * esp + dblshot * dblshotQty;
double totalTea = teaQty * tea;
System.out.println("Order: \n "+coffQty + " Coffee"
+ "\n "+creamQty +" Cream"
+ "\n "+sugarQty + " Sugar"
+ "\nTotal Coffee: "+ totalCoff);
System.out.println(" "+teaQty + " Tea"
+ "\nTotal Tea: "+ totalTea);
System.out.println(" "+espQty + " Espresso"
+ "\n "+dblshotQty +" Double shot"
+ "\nTotal Espresso: "+ totalEsp);
double totalBill = totalCoff+totalEsp+totalTea;
System.out.println("\nTotal drink order: "+totalBill);
}
break;
} // end while
}
} // end of class

Your code structure is making things difficult for you. As mentioned by #Carcigenicate, (nice name btw), you have you declared a method inside the main method. Once you change that, you'll notice now that now the display method shows compiler errors. This is because the variables referenced in display are no longer visible. You have a few options:
Rethink the design of the class i.e What methods should exist and how they will be called.
Take the display method outside the main method and then make the variables member variables that are visible to the methods you need. Read about the effects of using member variables first.
Remove the display method completely and move the logic to the main method.

I see a few main problems:
You defined display inside of main, inside of a while loop. You can't define methods inside of methods, let alone inside of loops. Move display outside of main, but still inside the class.
You have a misplaced break floating around under display. Get rid of that, as that will also be an error.
As #MiiinimalLogic pointed out, you're relying on data from main inside of display. You'll need to pass the data from main to display as arguments.

Related

Java Gas Station project coding troubles

I am a beginner at Java coding. Just started an online class less than 4 weeks ago. Im currently working on a project where I need to
traverse a logical decision to determine the need of a customer. Simulate a gas station that has 4 stations...
After piecing together what I know so far, I came up with the code below. It does have some yellow errors and when I run in Eclipse I only get the print out:
welcome to gas station, choose station number 1, 2 or 3.
Can I get some help on what to do from here please?
public static void main(String[] args) {
int stations;
keyboard2 = new Scanner(System.in);
System.out.print("Welcome to Gas Station \n");
System.out.println("Choose Station Number: \n");
System.out.println("1, 2, or 3 \n");
stations = keyboard2.nextInt(2);
switch (stations) {
case 1:
System.out.println("You entered Station 1.");
break;
case 2:
System.out.println("You entered Station 2.");
break;
case 3:
System.out.println("You entered Station 3.");
break;
default:
System.out.println("Error: Invalid Number");
}
}
private Scanner keyboard;
{
System.out.print("Choose your fuel type:\n");
System.out.println("Press 1 for Unleaded\n");
System.out.println("Press 2 for Unleaded Plus\n");
System.out.println("Press 3 for Unleaded Premium\n");
int gastype;
gastype = keyboard.nextInt(2);
switch (gastype) {
case 1:
System.out.println("You Chose Unleaded.");
break;
case 2:
System.out.println("You Chose Unleaded Plus.");
break;
case 3:
System.out.println("You Chose Unleaded Premium.");
break;
default:
System.out.println("Error: Invalid Number");
}
}
private Scanner keyboard1;
{
System.out.print("Enter gallon amount"
+ "Max amount 30 gallons)");
int numberGallons;
numberGallons = keyboard.nextInt(9);
}
double totalPayment = 0.0;
double numberGallons = 0;
double Unleaded = 0;
double UnleadedPlus = 0;
double UnleadedPremium = 0;
double tax = 0;
private static Scanner keyboard2;
{
Unleaded = 2.50;
UnleadedPlus = 3.00;
UnleadedPremium = 3.50;
tax = 3.5;
totalPayment = numberGallons + Unleaded * tax;
System.out.println("total gas amount: " + numberGallons
+ "\ntotal payment:" + Unleaded * tax + "\nthank you");
}
You seem to be missing knowledge about the structure of a class and need more practice at indenting / paying attention to bracket, if I remove parts of your code with placeholders, and indent things correctly (which can be simulated by "folding" those sections of code in your IDE, and auto formatting).
public static void main(String[] args)
{//Start main method
int stations;
keyboard2 = new Scanner(System.in);
System.out.print("Welcome to Gas Station \n");
System.out.println("Choose Station Number: \n");
System.out.println("1, 2, or 3 \n");
stations = keyboard2.nextInt(2);
switch (stations)
{
case 1:
System.out.println("You entered Station 1.");
break;
case 2:
System.out.println("You entered Station 2.");
break;
case 3:
System.out.println("You entered Station 3.");
break;
default:
System.out.println("Error: Invalid Number");
}//End Switch
}//End Main Method
private Scanner keyboard;
{
//Snip 1
}
private Scanner keyboard1;
{
//Snip 1
}
//Marker 2
double totalPayment = 0.0;
double numberGallons = 0;
double Unleaded = 0;
double UnleadedPlus = 0;
double UnleadedPremium = 0;
double tax = 0;
private static Scanner keyboard2;
{
//Snip 1
}
}//Class End
The sections I've commented with //Snip 1 are outside your main method, java is interpreting these as class initializers.
(see https://www.dummies.com/programming/java/what-is-an-initializer-in-java/)
These are NOT running with your main method, and not actually running at all, as they arn't static class initializers.
private Scanner keyboard;
private Scanner keyboard1;
and the other fields below //Marker 2 are being defined in the class instance scope.
You main method, like all main entry points, is static, there is no classes yet initialized, so anything in the class instance scope is not running, and no class initializers have been run.
To fix this, simply delete the //End Main Method bracket, create another at the very end of your class, and everything will be included in the main method again. I recommend auto formatting your code at this point.
Eclipse will complain about the fields, which will now be turned into local variables as they will be defined in the scope of the main method, so you can fix that by removing the access modifier 'private' in front of keyboard, keyboard1. In fact, you can use the same keyboard variable as a local variable for each time you use it, even without making it a field in the class.
Hope this helps.
Edit: It appears you may have been attempting to split this into multiple methods, and getting them confused with fields. If so, you need to read up on how to declare methods, just specifying {} after a field isn't enough.
In this case Snip 1 would be marking where you attempted to create new methods.
you would need to specify them as
private static void keyboard1()
{
Scanner keyboard1 = new Scanner(System.in);
//Snip1
};
in this case, private void keyboard1() has NO relation to Scanner keyboard1 and can be named whatever is convenient. You would then need to go on to calling this method in your main method. As it is static, you are safe to do so, but if you need multiple gas stations, you would need to make them non static, and initialize an instance.
If you get stuck passing variables between methods, you can either 1. declare them as fields in the class (noting that they will have to be static, since you are accessing them in the static main method, without instantiating a class.) Or pass them as arguments to the method.

java looping program cant detect symbols

I have a little issue with this program I am writing. When I run this with CMD it gives me a few errors such as the variable "totalFry" cant be defined even though it is a Global Variable. Any Help would be great, thank you very much!
(Note: this is my first time writing looping/ while code)
The idea is to give the user 3 choices, have the user input an option
(1-3) and have said options appear to prompt the user to input the
amount they want for said team.
Next, the program will ask the user
if they want to end the order, assuming they input "Yes" the program
will ask if the user wants to end the program if the user inputs
"yes" the program will go and total up the cost and display it.
End of program
Code:
import java.io.*;
import java.util.Scanner;
//Lab 4_5
public class Lab4_5 {
static Scanner keyboard = new Scanner(System.in);
// Declare local variables
static double totalBurger, totalFry, totalSoda;
static int option, burgerCount, fryCount, sodaCount;
// The main method
public static void main(String[] args) {
//Add a loop to run program again
String endProgram = "no";
while (endProgram.equals("no"))
//Add a loop to take in order
String endOrder = "no";
while (endOrder.equals("no"))
// Add statements to display the menu, get the user choice, and assign it to option
System.out.println("Enter 1 for Yum Yum Burger");
System.out.println("Enter 2 for Grease Yum Fires");
System.out.println("Enter 3 for Soda Yum");
//Add a Select Case statement based on the value of option
int option = 0;
option = keyboardnextInt();
//When option = 1
if (option == 1)
double totalBurger = 0;
int burgerCount = 0;
System.out.println("Enter the number of burgers you want ");
burgerCount = keyboard.nextDouble();
totalBurger = totalBurger + burgerCount * .99;
//When option = 2
if (option == 2)
double totalFry = 0;
int fryCount = 0;
System.out.println("Enter the number of fires you want ");
fryCount = keyboard.nextDouble();
totalFry = totalFry + fryCount * .79;
//When option = 3
if (option == 3)
double totalSoda = 0;
int sodaCount = 0;
System.out.println("Enter the number of sodas you want ");
sodaCount = keyboardnext.Double();
totalSoda = totalSoda + sodaCount * 1.09;
//Imput if user wants to end order
System.out.println("Do you want to end your order? (Enter no to add more items ) ");
endOrder = keyboard.next();
//Call
clacTotal();
printReceipt();
//Ask user if they want to end the program
System.out.println("Do you want to end the program? (Enter no to process a new order) ");
endProgram = keyboard.next();
}
//Calculate the total amount
public static void calcTotal() {
double total = 0;
double tax = 0;
double subtotal = 0;
//Add statements to calc total with tax and call printReceipt
calcTotal = totalBurger + totalFry + totalSoda * .06;
}
public static void printReceipt() {
//Add statements to display the total as shown above
System.out.println("Your total is $" + calcTotal);
}
}
Your code has many issues including the following:
missing curly braces on beginning and end of if's and loops
creating duplicate variables.
using keyboard.nextDouble() on ints
plus some spelling mistakes.
The following code should at least compile and work as you wanted.
import java.util.Scanner;
public class Lab4_5 {
static Scanner keyboard = new Scanner(System.in);
// Declare local variables
static double totalBurger, totalFry, totalSoda, calcTotal;
static int option, burgerCount, fryCount, sodaCount;
// The main method
public static void main(String[] args) {
//Add a loop to run program again
String endProgram = "no";
while (endProgram.equals("no")){
//Add a loop to take in order
String endOrder = "no";
while (endOrder.equals("no")){
// Add statements to display the menu, get the user choice, and assign it to option
System.out.println("Enter 1 for Yum Yum Burger");
System.out.println("Enter 2 for Grease Yum Fires");
System.out.println("Enter 3 for Soda Yum");
//Add a Select Case statement based on the value of option
int option = 0;
option = keyboard.nextInt();
//When option = 1
if (option == 1){
totalBurger = 0;
burgerCount = 0;
System.out.println("Enter the number of burgers you want ");
burgerCount = keyboard.nextInt();
totalBurger = totalBurger + burgerCount * .99;
}
//When option = 2
if (option == 2){
System.out.println("Enter the number of fires you want ");
fryCount = keyboard.nextInt();
totalFry = totalFry + fryCount * .79;
}
//When option = 3
if (option == 3){
System.out.println("Enter the number of sodas you want ");
sodaCount = keyboard.nextInt();
totalSoda = totalSoda + sodaCount * 1.09;
}
//Imput if user wants to end order
System.out.println("Do you want to end your order? (Enter no to add more items ) ");
endOrder = keyboard.next();
}
calcTotal();
printReceipt();
//Ask user if they want to end the program
System.out.println("Do you want to end the program? (Enter no to process a new order) ");
endProgram = keyboard.next();
}
}
//Calculate the total amount
public static void calcTotal() {
//Add statements to calc total with tax and call printReceipt
calcTotal = totalBurger + totalFry + totalSoda * .06;
}
public static void printReceipt() {
//Add statements to display the total as shown above
System.out.println("Your total is $" + calcTotal);
}
}

Counter won't work to end loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am working on an assignment and it is working well so far. But several aspects aren't working. For starters, my counters for int total and int counter won't work. Also my if statements don't seem to be working. I have been scratching my head for several days now.
The assignment calls for a program to input the order number and will loop based on how many orders the customer has. It also calls for customer name, sign type(wood or plastic), the number of characters,and color of characters.
Some more information:
The base price for all signs is $20.
If sign is wood, add $10. If it is plastic add $5.
The first 5 letters/numbers are included in base price, and $2 for each additional character.
Black or white characters are included in base price, there is an additional $8 for colored letters.
If the total charge is more than $100 give 25% discount on total price.
Here is my code right now:
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
System.out.println("Enter your order number");
orderNumber = sc.nextInt();
counter=orderNumber;
counter--;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
do{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
if(signType == "wood") {
i+=10;
}
if(signType == "plastic") {
i+=5;
}
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
if(color != "white" || color != "black") {
i += 8;
}
total= i;
System.out.println("Total is: $" + total);
if( total > 100 ) {
total = (total * 0.25);
System.out.println("The total is " + total );
}
}
while(counter <= orderNumber);
}
}
I added comments to guide you through the changes I made. Also, remember to call the sc.NextLine() function after you get user input so that they can input something different next time (this is called 'flushing' the buffer).
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
//I changed the phrasing just because it is a little confusing
System.out.println("Enter your number of orders");
orderNumber = sc.nextInt();
counter = orderNumber;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
sc.nextLine();
//When you know how many times you want to repeat something (like when a user tells you how many) I prefer using a for-loop, a do while loop works as well though
for(int x=0; x<counter;x++)
{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
//When comparing Strings, there is a function that you can use to compare them rather than using '=='
// It is also good to use the 'equalsIgnoreCase()' function to be more user friendly and robust
if(signType.equalsIgnoreCase("wood")) {
i+=10;
}
if(signType.equalsIgnoreCase("plastic")) {
i+=5;
}
//Flush the buffer (I haven't tested if this is necessary or not, it is good practice though)
sc.nextLine();
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
//Same concept as above, the differene is the ! before the function to test if it is false or not
if(!color.equalsIgnoreCase("white") || !color.equalsIgnoreCase("black")) {
i += 8;
}
}
total = i;
//You will not want to print this out until the end due to the possibility of it being over $100
// System.out.println("Total is: $" + total);
if( total > 100 ) {
//Mathematically speaking, you are making your total a quarter of what the original is, rather than taking a quarter off. You want 75% rather than 25%
// total = (total * 0.25);
total = (total * 0.75);
}
System.out.println("Total is: $" + total);
}
}
You should set counter to the correct starting value (which is presumably 1 in your case):
orderNumber = sc.nextInt();
counter=1;
//counter=orderNumber;
//counter--;
Then at the end of the loop, you should increment your counter:
do{
//code
counter++;
}
while(counter <= orderNumber);

How do I make an exit for my loop?

This is for an assignment in my class. It is to make an automatic ordering system. I'm still new to Java so everything doesn't necessarily click just yet. I think most things work for the most part but the main thing I am having trouble with is making the loop itself and making an exit for it.
import java.util.Scanner;
public class Metal {
public static void main (String[] args) {
double PRICE1 = 5.00;
double PRICE2 = 7.00;
double PRICE3 = 3.50;
double PRICE4 = 0.75;
double TAX = 0.05;
System.out.println ("Metal Down Your Mouth Menu");
System.out.println ();
System.out.println ();
System.out.println ();
System.out.println ("1. Black Sabbath Burgers (Hamburgers With Black Buns) " + PRICE1);
System.out.println ("2. Rack of Lamb of God (Rack of Lamb) " + PRICE2);
System.out.println ("3. Texas Hippie Collar Greens (Collar Greens) " + PRICE3);
System.out.println ("4. Pepsi " + PRICE4);
System.out.println ("Press any other button to stop ordering.");
Scanner userInput = new Scanner(System.in);
int itemnumber = 0;
while (itemnumber < 1 || itemnumber > 4) {
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
}
System.out.print ("How many?");
int amount = userInput.nextInt();
double subtotal = 0;
double total = 0;
double price = 0;
double taxes = 0;
String name = "";
switch (itemnumber){
case 1: name = "Black Sabbath Burgers"; price = PRICE1; break;
case 2: name = "Rack of Lamb of God"; price = PRICE2; break;
case 3: name = "Texas Hippie Collar Greens"; price = PRICE3; break;
case 4: name = "Pepsi"; price = PRICE4; break;
}
subtotal = price * amount;
total = subtotal + total;
System.out.print("Price for items: " + subtotal);
System.out.print("Price Total: " + total);
}
This is my first time posting on this site, but I think I found your problem. There are two large errors, indicated by the arrows:
while (itemnumber >= 1 || <-- itemnumber <= 4) {
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
} <--
1) This should be a '&&' not a '||'. You want it to be within the range. Right now the number it reads has to be greater than or equal to 1 OR less than or equal to 4, which is all integers.
2) You close your loop prematurely. What your code does right now (after the && switch) is it takes numbers 1-4 and keeps repeating the "Enter the item number...." line until you put a number not in the range, then it continues.
The fix: there are a few ways to fix this. My fix would be thus, and the explanation will come after:
import java.util.Scanner;
public class Metal {
public static void main (String[] args) {
double PRICE1 = 5.00;
double PRICE2 = 7.00;
double PRICE3 = 3.50;
double PRICE4 = 0.75;
double TAX = 0.05;
System.out.println ("Metal Down Your Mouth Menu");
System.out.println ();
System.out.println ();
System.out.println ();
System.out.println ("1. Black Sabbath Burgers (Hamburgers With Black Buns) " + PRICE1);
System.out.println ("2. Rack of Lamb of God (Rack of Lamb) " + PRICE2);
System.out.println ("3. Texas Hippie Collar Greens (Collar Greens) " + PRICE3);
System.out.println ("4. Pepsi " + PRICE4);
System.out.println ("Press any other button to stop ordering.");
Scanner userInput = new Scanner(System.in);
int itemnumber = 0;
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
double total = 0;
while (itemnumber >= 1 && itemnumber <= 4) {
System.out.print ("How many?");
int amount = userInput.nextInt();
double subtotal = 0;
double price = 0;
double taxes = 0;
String name = "";
switch (itemnumber)
{
case 1: name = "Black Sabbath Burgers"; price = PRICE1; break;
case 2: name = "Rack of Lamb of God"; price = PRICE2; break;
case 3: name = "Texas Hippie Collar Greens"; price = PRICE3; break;
case 4: name = "Pepsi"; price = PRICE4; break;
}
subtotal = price * amount;
total = subtotal + total;
System.out.print("Price for items: " + subtotal);
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
}
System.out.print("Price Total: " + total);
}
}
Explanation: In essence, you had like 90% of it. I moved the mentioned '}' to the end here:
itemnumber = userInput.nextInt();
} <--
That way, it loops over this code until the user ends.
Additionally, your loop does not need much fixing. It can be used with the && fix. However, you have to put that top line before the loop.
System.out.print("Enter the item number of the item you wish to order: ");
itemnumber = userInput.nextInt();
And then you put the same line at the end of the loop to reset itemnumber. What your loop does is if itemnumber is between 1 and 4, it executes the following code. Otherwise, it stops. By checking before you enter the loop, you set itemnumber so that way the loop has something to check. And you put the next input at the end of the loop so that way your program finishes totaling its first execution before moving on to the next.
Additionally, you should move the variable 'total' out of the loop as seen above. If you keep looping over it and resetting it to 0, your total will output 0 every time. Best to keep the creation of total out of the loop, and its modification inside the loop.
Small tip, use System.out.println(); instead of System.out.print(); it puts the outputs on its own line. Looks a little nicer.
I think that covers it. If you want more explanation, I'd be more than happy to give it to you. Java is pretty fun once you get used to it. It just takes time. :D

Converting a command line game to an applet

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?
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).

Categories

Resources