Converting a command line game to an applet - java

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

Related

Trying to work off and input by the user to change a value

I am creating a small game-type program,
Firstly I'm asking the user to give his name,
Secondly, I'm asking the user to choose one of the spaceships,
Thirdly, I want the user to add 2 modification, to improve the stats...
Here is the problem, I want to change some values of the spaceship.
The problem is that I don't know how to determine the chosen spaceship and how to change its values. Example: The Heavy-type Armour is 90 right now​ if I add the Advanced Hull Armour modification, i want it to increase to 100
public class Game {
static void playerName() {
System.out.println("What's your name?:");
String name = Keyboard.readString();
System.out.println("Okay,"+name+" it is!\n");
}
static class StarShip {
String name;
String armour;
String attack;
String mobility;
}
public static void main (String args[]) {
System.out.println("Hello Rookie! \n");
playerName();
System.out.println("Let's pick your first ship!\n");
System.out.println("Choose one of these:");
//insert ships here:
StarShip ship1 = new StarShip();
ship1.name = "Heavy-type";
ship1.armour = "Armour=90";
ship1.attack = "Firepower=50";
ship1.mobility = "Mobility=40";
StarShip ship2 = new StarShip();
ship2.name = "Medium-type";
ship2.armour = "Armour=60";
ship2.attack = "Firepower=60";
ship2.mobility = "Mobility=60";
StarShip ship3 = new StarShip();
ship3.name = "Light-type";
ship3.armour = "Armour=20";
ship3.attack = "Firepower=60";
ship3.mobility = "Mobility=90";
System.out.println("1 -"+ship1.name+"- "+ship1.armour+" "+ship1.attack+" "+ship1.mobility);
System.out.println("2 -"+ship2.name+"- "+ship2.armour+" "+ship2.attack+" "+ship2.mobility);
System.out.println("3 -"+ship3.name+"- "+ship3.armour+" "+ship3.attack+" "+ship3.mobility);
int chosen = Keyboard.readInt();
switch (chosen) {
case 1:
System.out.println("Heavy-type! Excellent choice! Great armour and guns! \n");
break;
case 2:
System.out.println("Medium-type! An all-rounder, a mix of everything! \n");
break;
case 3:
System.out.println("Light-type! Fast and mobile, but has little armour! \n");
break;
}
System.out.println("Lets pimp out your ship! \n");
String advancedHull = "1 - Advanced Hull Armour - Armour +10";
String betterAmmo = "2 - Better Ammo \t - Firepower +10";
String booster = "3 - Booster \t\t - Mobility +10";
System.out.println(advancedHull+"\n"+betterAmmo+"\n"+booster);
}
}
Currently you the fields of the StarShip are all Strings, when you add two strings they are concatenated, eg "abc"+"def" = "abcdef" regardless of what they say. You want to use ints these are "java numbers" and add as you would expect eg 10 + 20 = 30
class StarShip {
String name;
int armour;
int attack;
int mobility;
}
...
StarShip ship1 = new StarShip();
ship1.name = "Heavy-type";
ship1.armour = 90;
ship1.attack = 50;
ship1.mobility = 40;
...
When the user selects the ship we want to save this chose into a variable, like so:
Starship chosenShip; // must be declared outside the switch statement
switch (shipChoice ) {
case 1:
System.out.println("Heavy-type! Excellent choice! Great armour and guns! \n");
chosenShip = ship1;
Break;
...
Assuming advancedHull is selected and you include logic similar to how ships are selected
if (modificationChoice = 1){
chosenShip.armour = chosenShip.armour + 10;
} ...
You may want to declare a toSting() methods in StarShip like so
#Override
public String toString() {
return name +" Armour=" + armour +", Firepower=" + attack +", Mobility=" + mobility;
}
This way you can call System.out.println(ship1.toString()) to print the ship info.
Example:
System.out.println(ship1.toString());
// outputs: Heavy-type Armour=90, Firepower=50, Mobility=40
ship1.armour += 10; // java shorthand for `ship1.armour + ship1.armour + 10`
System.out.println(ship1.toString());
// outputs: Heavy-type Armour=100, Firepower=50, Mobility=40

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.

Display bill total, Java public void display() error

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.

Non-gui checkout register menu: how to format it?

I'm stumped on how to format my menu. What I have so far isn't working but I know it could be better formatted and shorter. This is the description of the assignment. You can see that my approach isn't going to work but I don't know how to change my approach...
I'm pretty sure I need to use arrays but I'm not sure how to store a public array so any method can call and store information to it.
import java.util.Scanner;
/*
#author David Jacobsen
#version 10-23-16
*/
/*
CODE DESIGN:
-> Bring menu from basicMenu assingment [X]
-> Adapt for this assignment [X]
-> Add content for new menu style []
-> Adapt loop position from basicMenu []
-> Add interior loops []
-> Capitalize class name for *proper grammer* [X]
For Display Cart have three seperate totals for each item then divide by each total by its respective items total
to find the number of that item the customer has purchased and assign it to a varible to be added into menu print out.
For Print Recipt have the system call 'display cart' and add a subtotal, tax, and total printer to the end.
Loop with basic menu while looper. (method 'startOver').
*/
public class CheckoutCounter {
public static void main(String[] args) {
while (startOver() == true) {
//Define Menu Bins
//Top Menu Choice Printer
System.out.println("1. Purchase Items");
System.out.println("2. Display Cart");
System.out.println("3. Print Your Recipt");
System.out.println(" ");
//Choose 1, 2, or 3 Menu Input
double doubleA;
Scanner topMenu = new Scanner(System.in);
System.out.print("Please select and option, 1 - 3:");
doubleA = topMenu.nextDouble();
System.out.println(" ");
System.out.println("Good choice.");
System.out.println(" ");
//Method Chooser
//Menu Choice "Purchase Items"
if (doubleA <= 1) {
priceTotalDragonfruit = priceTotalDragonfruit + CheckoutCounter.purchaseItems();
}
//Menu Choice "Print Recipt"
else if (doubleA >= 3) {
CheckoutCounter.printRecipt();
}
//Menu Choice "Display Cart"
else {
CheckoutCounter.displayCart();
}
}
}
//Purchase Items Method
public static double purchaseItems() {
//Define Variables and Initialize
double dragonfruit = 5.99;
double organicBlasphemy = 99.99;
double dayOldAnswerToTheUniverse = 100000;
double total = 0;
double multiplier;
//Define Total Containers and Initialize
double priceTotalDragonfruit = 0;
double priceTotalOrganicBlasphemy = 0;
double priceTotaldayOldAnswerToTheUniverse = 0;
//Top Menu Choice Printer
System.out.println("1. Dragonfruit ($5.99/lb)");
System.out.println("2. Organic Blasphemy ($99.99 per comment)");
System.out.println("3. 1 Day Old Answer to the Universe ($100,000 per request)");
System.out.println(" ");
//Choose 1, 2, or 3 Menu Input
double doubleA;
Scanner topMenu = new Scanner(System.in);
System.out.print("Please select and option, 1 - 3:");
doubleA = topMenu.nextDouble();
System.out.println(" ");
System.out.println("Good choice.");
System.out.println(" ");
//Method Chooser
//Menu Choice "Dragonfruit"
if (doubleA <= 1) {
System.out.println("How much/many do you want?");
Scanner multiplierScanner = new Scanner(System.in);
System.out.println("Enter amount here:");
multiplier = multiplierScanner.nextDouble();
System.out.println("We added your item(s) to your cart.");
priceTotalDragonfruit = total + (5.99 * multiplier);
}
//Menu Choice "1 Day Old Answer to the Universe"
else if (doubleA >= 3) {
System.out.println("How much/many do you want?");
Scanner multiplierScanner = new Scanner(System.in);
System.out.println("Enter amount here:");
multiplier = multiplierScanner.nextDouble();
System.out.println("We added your item(s) to your cart.");
priceTotaldayOldAnswerToTheUniverse = total + (100000 * multiplier);
}
//Menu Choice "Organic Blasphemy"
else {
System.out.println("How much/many do you want?");
Scanner multiplierScanner = new Scanner(System.in);
System.out.println("Enter amount here:");
multiplier = multiplierScanner.nextDouble();
System.out.println("We added your item(s) to your cart.");
priceTotalOrganicBlasphemy = total + (99.99 * multiplier);
}
}
//Display Cart Method
public static void displayCart() {
}
//Print Recipt/End Program Method
public static void printRecipt() {
}
//Start Over Loop Method
public static boolean startOver() {
Scanner inputScanner = new Scanner(System.in);
System.out.print("Please enter either 'True', to continue, or 'False', to stop: ");
Boolean userInputA;
userInputA = inputScanner.nextBoolean();
boolean goAhead;
if (userInputA == false) {
goAhead = false;
}
else {
goAhead = true;
}
return goAhead;
}
}
This is actually a good exercise for a student like you. I wont give you the exact answer (there are many ways though) but let me help you analyze this.
Java is an OOP language. The first thing to do is always determine what your domain objects would be.
Based on your requirement, it is asking for a Menu and create a method for each of the things it does. (sounds like an Object, yes?)
It should look something like below:
public class Menu{
public void purchaseItems(){ // pass an argument or return something depending on what you need
// figure out how you purchase items
}
public void displayCurrentPurchases(){
// figure out how you display the cart (your cart can be a List, Map, or even a class)
}
public void printReceipt(){
// figure out how you print the receipt
//somewhere here you would need to call your computeTaxes method
double netAmount = computeTaxes(grossAmount);
}
/* It's a good idea to limit a method to doing only one thing as much as possible, so you might need to make private methods such as computing for taxes below */
private double computeTaxes(double totalAmount){
return total * 0.098;
}
// and so on...
}
Now that you've got your Menu object set, you can create your Main class to actually create an instance of your Menu:
public class MainClass{
public static void main(String[] args) {
Menu menu = new Menu();
/* create your scanner here, and call the methods on the Menu depending on the user's choice */
// a switch for the user's selection might be a good idea:
switch(selected){
case 1:
menu.purchaseItems();
break;
case 2:
// you get the point. I leave this to you.
default:
sysout("Invalid selection");
break;
}
}
}

How to calculate percentage base on user input in java

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

Categories

Resources