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.
Related
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.
I made a program to calculate total price based on user's input. It is working fine, but i would like to know how to cut the code but to have the same output.
Especially on IF ELSE statement, I would like to know how not to repeat myself in those blocks. Is there any other way I can write ouputs after IF ELSE blocks, or they have to be individually inside of those blocks? Thanks.
Here is the code
import java.util.Scanner;
import java.text.*;
public class GasCalc
{
public static void main(String[] args)`enter code here`
{
double gasPrice,carGallons,fullTank,totalPrice;
Scanner input=new Scanner(System.in);
System.out.print("Do you want to calculate full tank (y/n) ");
String askMe=input.next();
if
(askMe.equalsIgnoreCase("y"))
{
DecimalFormat num=new DecimalFormat("$,###.00");
System.out.print("What is the price of 1 gallon of gas ? ");
gasPrice=input.nextDouble();
System.out.print("How many gallons does your vehicle accept ? ");
fullTank=input.nextDouble();
totalPrice=gasPrice*fullTank;
System.out.println("You will pay "+num.format(totalPrice)+" for the full tank of gas");
}
else
if(askMe.equalsIgnoreCase("n"))
{
DecimalFormat num=new DecimalFormat("$,###.00");
System.out.print("How many gallons do you need ? ");
carGallons=input.nextDouble();
System.out.print("What is the price of 1 gallon of gas ? ");
gasPrice=input.nextDouble();
totalPrice=gasPrice*carGallons;
System.out.println("You will pay "+num.format(totalPrice)+" for "+carGallons+" gallons of gas");
}
}
}
If I understand your question correctly - you don't want to repeat the same code in the 'if' and the 'else' parts of an if statement.
The way you would do this is to the same as anywhere else: extract the common code as a function/method which is called from both places.
You can move the last two statements outside, that way your calculation and printing can be done outside the if-else block.
You can rename fullTank and carGallons to gallons, so both variables have the same name, that way the last two statements can be used outside if-else.
totalPrice=gasPrice*gallons;
System.out.println("You will pay "+num.format(totalPrice)+" for the full tank of gas");
Use a method and factorize the local variable num, used in both if and else :
public class GasCalc {
private static double readDouble(Scanner in, String msg) {
System.out.print(msg);
return in.nextDouble();
}
private static String readString(Scanner in, String msg) {
System.out.print(msg);
return in.next();
}
public static void main(String[] args) {
double gasPrice, carGallons, fullTank, totalPrice;
Scanner input = new Scanner(System.in);
String askMe = readString(input,"Do you want to calculate full tank (y/n) ");
DecimalFormat num = new DecimalFormat("$,###.00");
if (askMe.equalsIgnoreCase("y")) {
gasPrice = readDouble(input,"What is the price of 1 gallon of gas ? ");
fullTank = readDouble(input,"How many gallons does your vehicle accept ? ");
totalPrice = gasPrice * fullTank;
System.out.println("You will pay " + num.format(totalPrice) + " for the full tank of gas");
} else if (askMe.equalsIgnoreCase("n")) {
carGallons = readDouble(input,"How many gallons do you need ? ");
gasPrice = readDouble(input,"What is the price of 1 gallon of gas ? ");
totalPrice = gasPrice * carGallons;
System.out.println("You will pay " + num.format(totalPrice) + " for " + carGallons + " gallons of gas");
}
}
}
You could actually factorize even more but it would make little sense to create another method for such a specific treatment. If you are using JDK 8 and understand the lambda expressions, go for it.
Did a little bit of research on this error and most seem simple. I checked to see if i had some spelling errors and I didnt notice any. Im trying to print a few lines using printf. When i go to compile this code it gives me a "cannot find symbol error". Could it be that the method these lines are in need to be in the method the variables are defined? The error is only being done in my printSales method.This isnt the finished product so i may be short a piece or two. But here is my code any help would be appreciated.
import java.util.Scanner;
public class Sales
{
public static void main( String[] args)
{
Scanner input = new Scanner (System.in);
System.out.print("Please enter a product number.");
double product1 = 0;
double product2 = 0;
double product3 = 0;
double product4 = 0;
double product5 = 0;
double sale;
int userInput = input.nextInt();
while(userInput != 0)
{
if(userInput >= 1 && userInput <= 5)
{
switch(userInput)
{
case 1: System.out.println("");
product1 ++;
sale += 2.98;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
case 2: System.out.println("");
product2 ++;
sale += 4.50;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
case 3: System.out.println("");
product3 ++;
sale += 9.98;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
case 4: System.out.println("");
product4 ++;
sale += 4.49;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
case 5:System.out.println("");
product5 ++;
sale += 6.87;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
}//end switch
} //end if
else if (userInput != 0)
bSystem.out.println("ERROR: Incorrect Product Number, Please Try Again");
System.out.print("");
userInput = input.nextInt();
}//end while
} //end main
public void printSales()
{
System.out.println();
System.out.printf("Product 1: $%.2f\n", product1);
System.out.printf("Product 2: $%.2f\n", product2);
System.out.printf("Product 3: $%.2f\n", product3);
System.out.printf("Product 4: $%.2f\n", product4);
System.out.printf("Product 5: $%.2f\n", product5);
} //end printSales
} //end class
This is a problem with the scope of your variables. You cannot refer to variables from one method in another method. Try redefining printSales:
public void printSales(int product1, int product2, int product3, int product4, int product5)
{
System.out.println();
System.out.printf("Product 1: $%.2f\n", product1);
System.out.printf("Product 2: $%.2f\n", product2);
System.out.printf("Product 3: $%.2f\n", product3);
System.out.printf("Product 4: $%.2f\n", product4);
System.out.printf("Product 5: $%.2f\n", product5);
} //end printSales
and then of course you will have to change how you call printSales (which I see you are not calling now, but perhaps you will call it in the future):
printSales(product1, product2, product3, product4, product5);
Be sure that product1, product2, etc are all in the same "scope"-- you can't reach into another method, or into an if{} or for{} or while{} block to reference variables.
Four problems...
1
sale might not be initialised...
You declare the sale variable as...
double sale;
As a local variable, it has no default value, so doing something like sale += 2.98 has undefined results.
Simple initialize the variable to a default/starting value...
double sale = 0d;
2
package bSystem does not existbSystem.out.println("ERROR: Incorrect Product Number, Please Try Again");
Typo, it should be System.out.println ;)
3
error: cannot find symbol
System.out.printf("Product 1: $%.2f\n", product1);
The values product1, product2, product3, product4 and product5 have no meaning in printSales as they've only been declared as local variables within main.
Normally, I would suggest making these instance variables, but because you're running within a static context of main, this won't work. Instead, modify the printSales method to take parameters...
public void printSales(double product1, double product2, double product3, double product4, double product5) {
...
}
4
You should be getting a number of warnings about 'unreachable statement, this caused by the fact that youbreakout of theswitch` statement, but attempt to execute code after it...
case 1:
System.out.println("");
product1++;
sale += 2.98;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
^--- These can't be executed, because of the break before it...
Instead, try moving the code before the break statement....
case 1:
System.out.println("");
product1++;
sale += 2.98;
System.out.print("How many were sold?");
userInput = input.nextInt();
break;
You might like to take a look at the Variables trail and Defining Methods for some more details
The variables "double product1/2/3..." are local variables, i.e. their scope and life-cycle are restricted inside the main method - you cannot reach them from printSales().
To solve the problem and be able to modify/call the variables, make them as fields instead. That is, place them inside the context of the class and not a method.
public class Sales
{
//variables moved into the context of the class, i.e. you can reach them from
//all methods of this class. Furhermore, they have to be static in order to be
//accessed from a static method.
private static double product1 = 0;
private static double product2 = 0;
private static double product3 = 0;
private static double product4 = 0;
private static double product5 = 0;
private static double sale;
public static void main( String[] args)
{
Scanner input = new Scanner (System.in);
System.out.print("Please enter a product number.");
//rest of main method but without vairables
}
So basically I have this survey program and I want to know how to calculate the percentage of questions answered that match the response given by the "if" statements. but this percentage can vary based on what the user types. another thing is that I need to put the code for calculating percentage into a non-main method which I have already setup and commented on (labeled non-main method) in the code below. What i want to know is how to make a formula that will account for all possible user inputs (basically 1/5, 2/5, 3/5, 4/5 and 5/5 since the survey is 5 questions) .
import java.util.Scanner;
public class VideogameSurveyFINAL {
//non-main method
private static void gamerpercentagelikeme (String[] args) {
int correct
}
//main method below
public static void main(String[] args) {
boolean run = true;
while(run){
System.out.println ("WELCOME TO THE GRAND SURVEY OF VIDEOGAMES!");
System.out.println ("");
Scanner keyboard = new Scanner(System.in);
//Q1
System.out.println("Question 1: Do you like Videogames? (Please answer Yes or No)");
String input = keyboard.nextLine();
if (input.equalsIgnoreCase("Yes")||input.equalsIgnoreCase("Yeah")||input.equalsIgnoreCase("Y")||input.equalsIgnoreCase("YES!")) {
System.out.println("Awesome!");
}
else {
System.out.println("Wow. You have no sense of fun.");
}
//Q2
System.out.println ("");
System.out.println("Question 2: What types of videogames do you play?(Please use abbreviated froms of games such as FPS, MMO, RPG etc).");
String input2 = keyboard.nextLine();
if (input2.equalsIgnoreCase("Fps")) {
System.out.println("Fantastic! Me too!");
}
else {
System.out.println("OK, thats cool!My favorite is FPS.");
}
//Q3
System.out.println ("");
System.out.println("Question 3:Do you like Singleplayer or Multiplayer games? ");
String input3 = keyboard.nextLine();
if (input3.equalsIgnoreCase("Singleplayer")||input.equalsIgnoreCase("S")||input.equalsIgnoreCase("SP")) {
System.out.println("Me Too!!");
}
else {
System.out.println("Rad! My favorite is Singleplayer. ");
}
//Q4
System.out.println ("");
System.out.println("Question 4: What do you like in a videogame");
String input4 = keyboard.nextLine();
if (input4.equalsIgnoreCase("I dont play games")||input.equalsIgnoreCase("None")||input.equalsIgnoreCase("N")) {
System.out.println("You are sooooo boring.");
}
else {
System.out.println("Awesome! What I like in a videogame is solid gameplay, great graphics and immersive audio...but most of all, IT HAS TO BE FUN!!");
}
//Q5
System.out.println ("");
System.out.println("Question 5: What is your ALL-TIME favorite videogame?");
String input5 = keyboard.nextLine();
if (input5.equalsIgnoreCase("Skyrim")) {
System.out.println("Really?! ME TOO!");
}
else {
System.out.println("Great! My personal favorite is SKYRIM!");
}
System.out.println ("");
System.out.println("THANK YOU FOR TAKING THE GRAND SURVEY OF VIDEOGAMES!");
System.out.println ("");
System.out.println ("Would you like to take the survey again? (Please answer with Yes or No: Case sensitive)");
String input6 = keyboard.nextLine();
if (input6.equalsIgnoreCase("No")) {
break;
}
else
{
System.out.println("Okay! The Survey will restart shortly.");
System.out.println ("");
System.out.println ("");
}
}
}
}
Right inside of public static void main(String[] args) { declare a public variable like:
int questionsCorrect = 0; //this is where we will keep track of the questions 'correct'
Now every time we get a question right, we will increment this count.
Inside of the if(condition...) statements, we will do this increment.
For example:
if (input.equalsIgnoreCase("Yes")||input.equalsIgnoreCase("Yeah")||input.equalsIgnoreCase("Y")||input.equalsIgnoreCase("YES!")) {
System.out.println("Awesome!");
questionsCorrect++; //increment number of questions correct by 1
}
do this for every question in the survey.
Now for the percentage... I believe that it would be wise to change the private static void gamerpercentagelikeme (String[] args) method's parameters to take the questions correct and the total questions, then returning the percentage in decimal form.
private static double gamerpercentagelikeme (int correct, int total){
return correct/total;
}
Now at the end when we want to display the answer, we can call:
double results = gamerpercentagelikeme(questionsCorrect, TOTAL_QUESTIONS); //note: declare TOTAL_QUESTIONS before using it.
double percentageLikeMe = results * 100;
System.out.println(percentageLikeME + "% like me.);
Hope this helps.
If i'm understanding correctly, you need to calculate the percentage of questions that the user got right?
You need to have a new field that is an int that stores the number of questions they got right, initialized to zero. Then every time they get a question right you increment this total by one.
Then at the end of the program you do that field divided by the total number of questions
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).