I'm making a currency tracker to track the live value of bitcoin.
the class "bitcoinlive" runs Correctly if I run it in its own main method, but it won't work when I make an instance of the file. I need it to print the live value you of bitcoin.
I try to print out the variable "a53" but I don't know if I'm doing it right.
Here are the list of imports for the bitcoinlive class because it kept giving me an error message and wouldn't allow this to be apart of the code when posting this.
public static void main(String[] args) {
Dates d = new Dates();
String s = d.getDate();
System.out.println("Date is" + s);
W3 mywallet = new W3();
Bitcoinlive mybitcoinlive = new Bitcoinlive();
L3 myledger = new L3();
Scanner myscanner = new Scanner(System.in);
double buy = 0.0;
int choice = 0;
double bitcoin = 4000;
double USD = 20000;
while (choice != 5) {
System.out.println("Welcome! Enter a command. \n"
+ "Enter 1) Buy Bitcoin \n"
+ "Enter 2) Sell Bitcoin \n"
+ "Enter 3) Print Balance \n"
+ "Enter 4) Print History \n"
+ "ENTER 5) Exit Program\n");
choice = myscanner.nextInt();
if (choice == 1) {
System.out.println("How many? ");
buy = myscanner.nextDouble();
mywallet.add(buy);
bitcoin = bitcoin * buy;
USD = USD - bitcoin;
myledger.save(s);
System.out.println("you have bought:" + mywallet.numcoins);
System.out.println(USD);
System.out.println(mybitcoinlive.a53);
bitcoin = 4000;
} else if (choice == 2 && USD >= bitcoin) {
System.out.println("How many?");
buy = myscanner.nextDouble();
mywallet.subtract(buy);
System.out.println("you have sold:" + mywallet.numcoins);
USD = USD + bitcoin;
System.out.println(USD);
bitcoin = 4000;
myledger.save(s);
} else if (choice == 3) {
System.out.println("Balance:" + mywallet.numcoins);
} else if (choice == 4) {
System.out.println("Transaction history: ");
System.out.println("you have made" + myledger.getsize() + "transactions"
+ d.getDate());
} else if (choice == 5) {
// exit
break;
} else if (choice == 7) {
System.out.println(mybitcoinlive.price);
}
}
System.out.println("Bye");
}
this is my separate class
public class Bitcoinlive {
Double a53=0.0;
double price;
Double get() {
try {
String urlcoincapeth13 = "https://api.coinmarketcap.com/v1/ticker/bitcoin/";
Document docblocktradescoincapeth13 = Jsoup.parse(new URL(urlcoincapeth13).openStream(), "UTF-8", "", Parser.xmlParser());
String a13 = docblocktradescoincapeth13.toString();
int a23 = a13.indexOf("price_usd") + 13;
int a33 = a13.indexOf("price_btc") - 4;
String a43 = a13.substring(a23, a33);
a53 = Double.parseDouble(a43);
} catch (Exception e) {
System.out.println("Error accessing bitcoin values");
}
return a53;
}
}
Your class Bitcoinlive stores the price in a field called a53. You can update this field by calling get(). However, it looks like you're never calling get() - you're just calling the field:
System.out.println(mybitcoinlive.a53);
Try replacing that line with:
System.out.println(mybitcoinlive.get());
Or refresh it first:
mybitcoinlive.get();
System.out.println(mybitcoinlive.a53);
Related
I'm trying to compare the cost of a user's phone usage under plans from three
different providers. I can get as far as entering the usage details but once entered I try to call the method to rerun from the if statement but it just displays the main menu again and stops. I want it to run through the entire if statement from the start again
import java.util.Scanner;
public class MainMenuSelection {
public static int menuSel() {
int menuSel ;
System.out.println("ENTER USAGE DETAILS MENU\n");
System.out.println("Please select an option from the menu:");
System.out.println("1.Phone Call");
System.out.println("2.SMS ");
System.out.println("3.Data usage");
System.out.println("4. Return to main menu");
Scanner in = new Scanner(System.in);
System.out.println("Enter selection: ");
menuSel = in.nextInt();
while (menuSel < 1 || menuSel >4){
System.out.println("Value must bebetween 1 and 4, plese try again.");
System.out.println("Enter your selection: ");
menuSel = in.nextInt();
}
return menuSel;
}
public static int mainMenuSelection() {
System.out.println("MAIN MENU\n");
System.out.println("Please select from the menu:");
System.out.println("1. Enter Usage details");
System.out.println("2. Display Cost under provider 1");
System.out.println("3. Display Cost under provider 2");
System.out.println("4. Display Cost under provider 3");
System.out.println("5. Clear usage details");
System.out.println("6. Exit System");
int mainMenuSelection;
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
//return mainMenuSelection;
while (mainMenuSelection < 1 || mainMenuSelection >6){
System.out.println("Value must bebetween 1 and 6, plese try again.");
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
}
System.out.println("You chose selection " + mainMenuSelection + "\n");
return mainMenuSelection;
}
public static void main(String[] args) {
System.out.println("Hello World!");
int callLength = 0;
int numSMS = 0;
int numberOfMB = 0;
int numberofCalls;
int callTime;
int totalcallTime = 0;
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
int menuSel = menuSel();
if (menuSel == 1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of phone call you have made? ");
numberofCalls = in.nextInt();
for (int i = 0; i < numberofCalls; i++) {
Scanner callInput = new Scanner(System.in);
System.out.println("How long was the call in seconds?");
callTime = callInput.nextInt();
totalcallTime = callTime + totalcallTime;
}
System.out.println("Your total number of calls is " + numberofCalls);
System.out.println("Your total call time is " + totalcallTime + " seconds" + "\n");
} else if (menuSel == 2) {
System.out.println("Enter the number of SMS messages: ");
//int numSMS;
Scanner userNumSMS = new Scanner(System.in);
numSMS = userNumSMS.nextInt();
System.out.println("Your number of SMSs is " + numSMS + "\n");
} else if (menuSel == 3) {
System.out.println("Enter the amount of data in MB: ");
//int numberOfMB;
Scanner userNumMB = new Scanner(System.in);
numberOfMB = userNumMB.nextInt();
System.out.println("Your amount of data in MB is " + numberOfMB + "\n");
} else {
mainMenuSelection(); // go back to main menu
}
} else if (mainMenuSelection == 2) {
//Display cost under provider 1
double callCost = 0.03 * totalcallTime;
double smsCost = 0.10 * numSMS;
double dataCost = 0.02 * numberOfMB;
double totalCostProvider1 = callCost + smsCost + dataCost;
System.out.println(totalCostProvider1);
} else if (mainMenuSelection == 3) {
//Display cost under provider 2
double callCost2 = 0.04 * totalcallTime;
double smsCost2 = 0.12 * numSMS;
double dataCost2 = 0.04 * numberOfMB;
double totalCostProvider2 = callCost2 + smsCost2 + dataCost2;
System.out.println(totalCostProvider2);
} else if (mainMenuSelection == 4) {
//Display cost under provider 3
double callCost3 = 0.05 * totalcallTime;
double smsCost3 = 0.11 * numSMS;
double dataCost3 = 0.03 * numberOfMB;
double totalCostProvider3 = callCost3 + smsCost3 + dataCost3;
System.out.println(totalCostProvider3);
} else if (mainMenuSelection == 5) {
//clear usage details
} else {
System.out.println("Exiting System");
System.exit(0);
}
mainMenuSelection = mainMenuSelection();
}
}
Codes run from top to bottom. Therefore, after the int mainMenuSelection = mainMenuSelection(); and the if-else statement is run, the code would run once again for the mainMenuSelection = mainMenuSelection() and ends, as there is nothing left in the block.
A fairly simple solution would be using a while or do-while loop with a boolean checking if the user entered the number 6 to exit the system.
You can try this example:
public static void main(String[] args) {
/*
* Your variables here
*/
boolean isExit = false;
while(!isExit) {
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
// menuSel codes here
} else if (mainMenuSelection == 2) {
// Display cost under provider 1
} else if (mainMenuSelection == 3) {
// Display cost under provider 2
} else if (mainMenuSelection == 4) {
// Display cost under provider 3
} else if (mainMenuSelection == 5) {
// Clear usage details
} else {
System.out.println("Exiting System");
isExit = true;
}
}
Hopes this answer helps you well.
It looks like you need a loop. Your main method has an exit condition so you can essentially loop forever by wrapping the code in your main method with a while loop:
public static void main(String[] args) {
while(true) {
// your main method code in here
}
}
By the way, you need to edit your code above in good formatting.
I have added a while loop in your main. Also, whenever any unwanted number the loop will exit using a break; and that in turn stops the program.
mainMenuSelection = mainMenuSelection();
I have deleted the above line from the code so you just need to call it once at the beginning of the code.
Let me know if you need sth else!
import java.util.Scanner;
public class MainMenuSelection {
public static int menuSel() {
int menuSel;
System.out.println("ENTER USAGE DETAILS MENU\n");
System.out.println("Please select an option from the menu:");
System.out.println("1.Phone Call");
System.out.println("2.SMS ");
System.out.println("3.Data usage");
System.out.println("4. Return to main menu");
Scanner in = new Scanner(System.in);
System.out.println("Enter selection: ");
menuSel = in.nextInt();
while (menuSel < 1 || menuSel > 4) {
System.out.println("Value must bebetween 1 and 4, plese try again.");
System.out.println("Enter your selection: ");
menuSel = in.nextInt();
}
return menuSel;
}
public static int mainMenuSelection() {
System.out.println("MAIN MENU\n");
System.out.println("Please select from the menu:");
System.out.println("1. Enter Usage details");
System.out.println("2. Display Cost under provider 1");
System.out.println("3. Display Cost under provider 2");
System.out.println("4. Display Cost under provider 3");
System.out.println("5. Clear usage details");
System.out.println("6. Exit System");
int mainMenuSelection;
Scanner userInput = new Scanner(System.in);
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
//return mainMenuSelection;
while (mainMenuSelection < 1 || mainMenuSelection > 6) {
System.out.println("Value must bebetween 1 and 6, plese try again.");
System.out.println("Enter your selection: ");
mainMenuSelection = userInput.nextInt();
}
System.out.println("You chose selection " + mainMenuSelection + "\n");
return mainMenuSelection;
}
public static void main(String[] args) {
int callLength = 0;
int numSMS = 0;
int numberOfMB = 0;
int numberofCalls;
int callTime;
int totalcallTime = 0;
while (true) {
int mainMenuSelection = mainMenuSelection();
if (mainMenuSelection == 1) {
int menuSel = menuSel();
if (menuSel == 1) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of phone call you have made? ");
numberofCalls = in.nextInt();
for (int i = 0; i < numberofCalls; i++) {
Scanner callInput = new Scanner(System.in);
System.out.println("How long was the call in seconds?");
callTime = callInput.nextInt();
totalcallTime = callTime + totalcallTime;
}
System.out.println("Your total number of calls is " + numberofCalls);
System.out.println("Your total call time is " + totalcallTime + " seconds" + "\n");
} else if (menuSel == 2) {
System.out.println("Enter the number of SMS messages: ");
//int numSMS;
Scanner userNumSMS = new Scanner(System.in);
numSMS = userNumSMS.nextInt();
System.out.println("Your number of SMSs is " + numSMS + "\n");
} else if (menuSel == 3) {
System.out.println("Enter the amount of data in MB: ");
//int numberOfMB;
Scanner userNumMB = new Scanner(System.in);
numberOfMB = userNumMB.nextInt();
System.out.println("Your amount of data in MB is " + numberOfMB + "\n");
}
} else if (mainMenuSelection == 2) {
//Display cost under provider 1
double callCost = 0.03 * totalcallTime;
double smsCost = 0.10 * numSMS;
double dataCost = 0.02 * numberOfMB;
double totalCostProvider1 = callCost + smsCost + dataCost;
System.out.println(totalCostProvider1);
} else if (mainMenuSelection == 3) {
//Display cost under provider 2
double callCost2 = 0.04 * totalcallTime;
double smsCost2 = 0.12 * numSMS;
double dataCost2 = 0.04 * numberOfMB;
double totalCostProvider2 = callCost2 + smsCost2 + dataCost2;
System.out.println(totalCostProvider2);
} else if (mainMenuSelection == 4) {
//Display cost under provider 3
double callCost3 = 0.05 * totalcallTime;
double smsCost3 = 0.11 * numSMS;
double dataCost3 = 0.03 * numberOfMB;
double totalCostProvider3 = callCost3 + smsCost3 + dataCost3;
System.out.println(totalCostProvider3);
} else if (mainMenuSelection == 5) {
//clear usage details
} else {
System.out.println("Exiting System");
System.exit(0);
break;
}
}
}
}
I have attempted using a nested if in the following code. I have initialized variables but the compiler is telling me that the variable named 'bill' is not initialized even though it has been. Why is the compiler not recognizing the value assigned to the variable? Please see the notes in the code below.
package killMe;
import java.util.Scanner;
public class Kill_Me {
static Scanner console = new Scanner(System.in);
static double PREMIUM_SERVICE = 55.00;
static double PREMIUM_DAY_OVERTIME_MIN = 0.20;
static double PREMIUM_NIGHT_OVERTIME_MIN = 0.15;
static double REGULAR_SERVICE = 30.00;
static double REGULAR_OVERTIME_MIN = 0.40;
public static void main(String[] args) {
int acctNumber;
double premiumDayMin;
double premiumNightMin;
double bill;
double minutes;
String name;
String premium = "PREMIUM";
String regular = "REGULAR";
System.out.println("What is the Account Number? ");
acctNumber = console.nextInt();
System.out.println("What is the Customer Name? ");
name = console.next();
System.out.println("Is the Service Code Premium or Regular? ");
String strService = console.next();
String strServiceCAP = strService.toUpperCase();
if(strServiceCAP.compareTo(premium) == 0)
{
System.out.println("How many Day Minutes were used? ");
premiumDayMin = console.nextDouble();
System.out.println("How many Night Minutes were used? ");
premiumNightMin = console.nextDouble();
if(premiumDayMin <0 && premiumNightMin <0)
{
System.out.println("Minutes cannot be less than 0 ");
}
else if(premiumDayMin <= 75 && premiumNightMin <= 100)
{
bill = PREMIUM_SERVICE;
}
else bill = PREMIUM_SERVICE + (premiumDayMin - 75) * PREMIUM_DAY_OVERTIME_MIN + (premiumNightMin - 100)
* PREMIUM_NIGHT_OVERTIME_MIN;
minutes = premiumDayMin + premiumNightMin;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Premium Service Used (Day): " + premiumDayMin);
System.out.println("Minutes Premium Service Used (Night): " + premiumNightMin);
System.out.println("Amount Due: " + bill); // I get an error here stating, "The local variable 'bill' may not have been initialized".
}
else if(strServiceCAP.compareTo(regular) == 0)
{
System.out.println("How many minutes were used? ");
minutes = console.nextDouble();
bill = REGULAR_SERVICE + (minutes - 50) * REGULAR_OVERTIME_MIN;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Regular Service Used: " + minutes);
System.out.println("Amount Due: " + bill); // I DO NOT receive an error message here.
}
else
{
System.out.println("Invalid Service Type");
}
} // End of main
} // End of class
No, bill has not been initialized in all cases.
Understand this: the Java compiler will never, ever, evaluate boolean expressions; Simplified version:
double bill;
if (c1) {
bill = v1;
} else if (c2) {
bill = v2;
}
// try and use bill here
Even if, according to your logic, boolean expressions c1 and c2 may cover all possible cases, the compiler cannot ensure that this is the case.
This is the root cause of your error, however deep your if/else, switch, etc statements may be nested.
They were some problems with else statement and variable declarations.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double PREMIUM_SERVICE = 25.00;
double PREMIUM_DAY_OVERTIME_MIN = 0.10;
double PREMIUM_NIGHT_OVERTIME_MIN = 0.05;
double REGULAR_SERVICE = 10.00;
double REGULAR_OVERTIME_MIN = 0.20;
int acctNumber;
double premiumDayMin;
double premiumNightMin;
double bill = 0.0;
double minutes;
String name;
String premium = "PREMIUM";
String regular = "REGULAR";
System.out.println("What is the Account Number? ");
acctNumber = console.nextInt();
System.out.println("What is the Customer Name? ");
name = console.next();
System.out.println("Is the Service Code Premium or Regular? ");
String strService = console.next();
String strServiceCAP = strService.toUpperCase();
if(strServiceCAP.compareTo(premium) == 0)
{
System.out.println("How many Day Minutes were used? ");
premiumDayMin = console.nextDouble();
System.out.println("How many Night Minutes were used? ");
premiumNightMin = console.nextDouble();
if(premiumDayMin <0 && premiumNightMin <0)
{
System.out.println("Minutes cannot be less than 0 ");
}
else if(premiumDayMin <= 75 && premiumNightMin <= 100)
{
bill = PREMIUM_SERVICE;
}
else
{
bill = PREMIUM_SERVICE + (premiumDayMin - 75) * PREMIUM_DAY_OVERTIME_MIN + (premiumNightMin - 100)
* PREMIUM_NIGHT_OVERTIME_MIN;
}
minutes = premiumDayMin + premiumNightMin;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Premium Service Used (Day): " + premiumDayMin);
System.out.println("Minutes Premium Service Used (Night): " + premiumNightMin);
System.out.println("Amount Due: " + bill); // I get an error here stating, "The local variable 'bill' may not have been initialized".
}
else if(strServiceCAP.compareTo(regular) == 0)
{
System.out.println("How many minutes were used? ");
minutes = console.nextDouble();
bill = REGULAR_SERVICE + (minutes - 50) * REGULAR_OVERTIME_MIN;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Regular Service Used: " + minutes);
System.out.println("Amount Due: " + bill); // I DO NOT receive an error message here.
}
else
{
System.out.println("Invalid Service Type");
}
} // End of main
}
I'm not sure why it gets this error, but try initialising bill as 0.00 when you declare the variable.
Also,
if(premiumDayMin <0 && premiumNightMin <0)
should probably be changed to
if(premiumDayMin <0 || premiumNightMin <0)
Because you want to make sure that either minutes is not less then zero. You're program should then probably handle this error, because the rest of the program still executes. But maybe you're getting on to that :-P.
I don't recall what I did to stop getting an error message (sorry) but I removed the code if(premiumDayMin <0 && premiumNightMin <0) and replaced it with if(premiumDayMin <= 75 && premiumNightMin <= 100) to stop the code from being redundant. That may have fixed things. I also added another else if to clean the logic up further.
I'm trying to make a virtual store program. Synopsis is if at any time the user enters 'q', the program should quit.
Once the user enters 'c', ask the user to enter a 2-character state such as CA, NV, WA. If a code other
than these three is entered, it falls under "other". Then display what is in their cart and the calculated
total price based on discounts and include the tax.
The problem is that the program would ask user for item and quantity once, then it goes into checkout mode. Whenever I put 'q', it goes to the next line.
Here is the code:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;
import java.io.*;
public class virtualStore {
public static void main(String [] args) throws IOException{
/* If the user enters an item number, the program should ask the user to enter how many of that item
they want, and then print the menu again. If at any time the user enters 'q', the program should quit.
Once the user enters 'c', ask the user to enter a 2-character state such as CA, NV, WA. If a code other
than these three is entered, it falls under "other". Then display what is in their cart and the calculated
total price based on discounts and include the tax. You should use the Math.round() and
System.out.printf methods to round numbers and to display to 2 decimal places. */
Scanner keyboard = new Scanner (System.in);
String input;
char c = ' ';
char q = ' ';
//tax rates
double CAtaxRate = .09;
double NVtaxRate = .07;
double WAtaxRate = .065;
double other = .06;
double tax = 0;
//checkout
double checkout = 0;
double total;
double cash = 0;
double change = 0;
//items
double mushrooms = 0.3;
double onions = 0.6;
double watermelon = 2.5;
double cookies = 1;
int item = 0;
//number of items
int numMushrooms = 0;
int numOnions = 0;
int numWatermelon = 0;
int numCookies = 0;
DecimalFormat dollar = new DecimalFormat("#,##0.00");
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to Alex's Store."
+ " Here is the menu. "
+ "\nEnter the item number to add it to your cart,"
+ " enter \'c\' to checkout or \'q\' to quit. ");
while(true)
//while(c != 'c' && c != 'q')
{
for (item = 1; item < 4; item ++){
System.out.println("Item\t\t\tPrice\t\t\tQuantity");
System.out.println("---------------------------------------------------------");
System.out.println("1. Mushrooms\t\t($0.30/$0.25)\t\t" + numMushrooms);
System.out.println("2. Onions\t\t($0.60/$0.50)\t\t" + numOnions );
System.out.println("3. Watermelon\t\t($2.50/$2.00)\t\t" + numWatermelon);
System.out.println("4. Cookies\t\t($1.00/$0.75)\t\t" + numCookies);
System.out.println("---------------------------------------------------------");
System.out.println("Enter item number between 1 through 4");
System.out.println("or enter 'c' for checkout or 'q' for quit.");
input = keyboard.nextLine();
item = Integer.parseInt(input);
if (input.equals("1"))
{
System.out.println("Enter how many items you want.");
String m = keyboard.nextLine();
numMushrooms = Integer.parseInt(m);
}
else if (input.equals("2"))
{
System.out.println("Enter how many items you want.");
String o = keyboard.nextLine();
numOnions = Integer.parseInt(o);
}
else if (input.equals("3"))
{
System.out.println("Enter how many items you want.");
String w = keyboard.nextLine();
numWatermelon = Integer.parseInt(w);
}
else if(input.equals("4"))
{
System.out.println("Enter how many items you want.");
String co = keyboard.nextLine();
numCookies = Integer.parseInt(co);
}
}
if (numMushrooms > 10)
{
mushrooms = 0.25;
}
else if (numOnions > 10)
{
onions = 0.5;
}
else if (numWatermelon > 10)
{
watermelon = 2;
}
else if (numCookies > 10)
{
cookies = .75;
}
// quit option
String quit = scanner.nextLine();
q = quit.charAt(0);
if (quit.equalsIgnoreCase("q"))
{
System.out.println("Goodbye");
scanner.close();
System.exit(0);
}
// checkout option
String ch = scanner.nextLine();
c = ch.charAt(0);
if (ch.equalsIgnoreCase("c"))
{
//checkout
checkout = numMushrooms * mushrooms + numOnions * onions + numWatermelon * watermelon + numCookies * cookies;
//tax
total = tax * checkout + checkout;
System.out.print("Enter state abbreviations: ");
input = keyboard.nextLine();
PrintWriter outputfile = new PrintWriter("receipt.txt");
outputfile.println("Your cart: ");
outputfile.println("Sub total:$ " + dollar.format(checkout));
if (input.equalsIgnoreCase("CA"))
{
total = CAtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + CAtaxRate);
outputfile.println("Tax: $" + dollar.format(CAtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase("NV"))
{
total = NVtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + NVtaxRate);
outputfile.println("Tax: $" + dollar.format(NVtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase("WA"))
{
total = WAtaxRate * checkout + checkout;
outputfile.println("Tax Rate: " + WAtaxRate);
outputfile.println("Tax: $" + dollar.format(WAtaxRate * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
else if (input.equalsIgnoreCase(input))
{
total = other * checkout + checkout;
outputfile.println("Tax Rate: " + other);
outputfile.println("Tax: $" + dollar.format(other * checkout));
outputfile.println("Total is: $" + dollar.format(total));
}
outputfile.println("-----------------------------------------------------");
input = keyboard.nextLine();
cash = Integer.parseInt(input);
outputfile.println("Enter amount of cash: $" + dollar.format(cash));
change = cash - total;
outputfile.println("Change due: $" + dollar.format(change));
outputfile.println("Thank you for shopping at Alex's store!");
outputfile.close();
FileWriter fw = new FileWriter("receipt.text", true);
PrintWriter pw = new PrintWriter(fw);
pw.println("C:\\Desktop\\Receipt.txt ");
pw.close();
}
}
}
}
You're using the wrong model to get user input.
Try doing something that looks like:
while(true) {
// Print the menu messages
String input = scanner.readLine();
if(input.equals("c")) {
// Read in and handle state abbreviation
} else if(input.equals("q")) {
System.exit(0);
} else {
int itemNumber = Integer.parseInt(input);
// Parse and handle item number
}
}
import java.util.Scanner;
public class TripCost
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String destination;
String hotel;
int days = 3;
double mealCost;
double regularMeal = 31.00;
double highCostMeal = 52.00;
double gasPrice = 3.29;
double miles;
double airfare;
double hotelCost;
double budgetel = 76.00;
double holidayInn = 109.00;
double sheraton = 138.00;
double hyatt = 215.00;
System.out.println("Here are the places you may go for vacation:");
System.out.println("--------------------------------------------");
System.out.println(" 1. Niagra Falls");
System.out.println(" 2. Chicago");
System.out.println(" 3. San Francisco");
System.out.println(" 4. Las Vegas");
System.out.println(" 5. St. Louis");
System.out.println("--------------------------------------------");
System.out.print("Please select the number of the destination: ");
int destinationChoice = keyboard.nextInt();
if (destinationChoice == 1)
{
miles = 257.00;
airfare = 0;
mealCost = regularMeal;
destination = "Niagra Falls";
}
else if (destinationChoice == 2)
{
miles = 303.00;
airfare = 0;
mealCost = highCostMeal;
destination = "Chicago";
}
else if (destinationChoice == 3)
{
miles = 0;
airfare = 630.00;
mealCost = highCostMeal;
destination = "San Francisco";
}
else if (destinationChoice == 4)
{
miles = 0;
airfare = 415.00;
mealCost = highCostMeal;
destination = "Las Vegas";
}
else if (destinationChoice == 5)
{
mealCost = regularMeal;
destination = "St. Louis";
System.out.print("Would you like to drive or fly? ");
String transportation = keyboard.next();
if (transportation.equalsIgnoreCase("drive"))
{
miles = 551.00;
airfare = 0;
}
else if (transportation.equalsIgnoreCase("fly"))
{
miles = 0;
airfare = 290.00;
}
else
{
System.out.print("Invalid selection");
System.exit(1);
}
}
else
{
System.out.print("Invalid destination");
System.exit(1);
}
System.out.println("These are the hotels with vacancies:");
System.out.println("------------------------------------");
System.out.printf("%-15s%10s%.0f\n", "1. Budgetel", "$", budgetel);
System.out.printf("%-15s%10s%.0f\n", "2. Holiday Inn", "$", holidayInn);
System.out.printf("%-15s%10s%.0f\n", "3. Sheraton", "$", sheraton);
System.out.printf("%-15s%10s%.0f\n", "4. Hyatt", "$", hyatt);
System.out.println("------------------------------------");
System.out.print("Which hotel would you like to stay at? ");
int hotelChoice = keyboard.nextInt();
if (hotelChoice == 1)
{
hotelCost = budgetel;
hotel = "Budgetel";
}
else if (hotelChoice == 2)
{
hotelCost = holidayInn;
hotel = "Holiday Inn";
}
else if (hotelChoice == 3)
{
hotelCost = sheraton;
hotel = "Sheraton";
}
else if (hotelChoice == 4)
{
hotelCost = hyatt;
hotel = "Hyatt";
}
else
{
System.out.print("Invalid selection");
System.exit(1);
}
System.out.println("Cost for your trip (drive to " + destination + ", staying at " + hotel + " for " + days + " days):");
System.out.println("---------------------------------------------------");
System.out.printf("%-13s%1s%3s%3.2f\n", "Transportation", ":", "$", miles/gasPrice);
}
}
down at the bottom where i go to print out the destination and hotel, it is saying that the local variables aren't initialized. How can I get my code so that the values assigned to these variables in my if statements carries over to the bottom?
Initialise your variables. For example, change
String destination;
to
String destination = null;
and the same for all the other variables that are not initialised.
if your String variable is not initialized will be a null value, so you need to initialize it's value, then when the variable goes through your if statements will get the right value for the result, you can declare String hotel=""; for example. hope to help
import java.util.Scanner;
public class CoffeeShop {
public static void main(String[] args) {
//Welcome message
String username;
System.out.println("Please enter your name");
Scanner keyboard = new Scanner(System.in);
username = keyboard.next();
System.out.println("Welcome to the Java Byte Code Coffee Shop," + username + "!");
//Menu
System.out.println("Here is our menu.");
System.out.println("1. Coffee $1.50");
System.out.println("2. Latte $3.50");
System.out.println("3. Cappuccino $3.25");
System.out.println("4. Expresso $2.00");
//Item selection
int item_Number;
System.out.println("Please enter an item number.");
Scanner item = new Scanner(System.in);
item_Number = item.nextInt();
if(item_Number == 1) {
item = 1.50;
}
if(item_Number == 2) {
item = 3.50;
}
if(item_Number == 3) {
item = 3.25;
}
if(item_Number == 4) {
item = 2.00;
}
//Item Quantity
int quantity;
System.out.println("Please enter the quantity.");
Scanner amount = new Scanner(System.in);
quantity = amount.nextInt();
double total = quantity * item;
System.out.println("Total before discount and tax is " + total);
//Discount and tax
double nuTotal;
if(total >= 10) {
nuTotal = total - (total * .1);
} else {
nuTotal = total;
}
System.out.println("Your total with discount is " + nuTotal);
double totalTax = nuTotal * .07;
System.out.println("Your total with tax is " + totalTax);
System.out.println("Thank you " + username + "! Please stop by again!");
}
}
Your assignment is to write a program called CoffeeShop (in the file CoffeeShop.java) that simulates a virtual coffee shop, allowing the user to select an item to purchase, along with the quantity of that item. After obtaining the item selection and desired quantity from the user, your program should calculate the cost, tax, discount, and final cost, then display these to the user.
The problem starts here:
Scanner item = new Scanner(System.in);
item_Number = item.nextInt();
if(item_Number == 1) {
item = 1.50;
}
if(item_Number == 2) {
item = 3.50;
}
if(item_Number == 3) {
item = 3.25;
}
if(item_Number == 4) {
item = 2.00;
}
item is a Scanner object but then you attempt to assign it a double value.
Then double total = quantity * item;. You multiply by a Scanner object.
Your error is in the following code.
First you declare:
Scanner item = new Scanner(System.in);
Then you try to set that scanner variable to be what I presume to be the price.
if(item_Number == 1) {
item = 1.50;
}
if(item_Number == 2) {
item = 3.50;
}
if(item_Number == 3) {
item = 3.25;
}
if(item_Number == 4) {
item = 2.00;
}
In order to fix this what you should do is set these numbers to a new variable, such as:
double price = 0;
price = ...; //not: item = ...;
Then you can calculate your total simply by:
double total = quantity * price;
Hope this helps! Just try to be very careful when setting variables :)
I believe your code should be similar to:
double price = 0;
if(item_Number == 1) {
price = 1.50;
}
if(item_Number == 2) {
price = 3.50;
}
if(item_Number == 3) {
price = 3.25;
}
if(item_Number == 4) {
price = 2.00;
}
double total = quantity * price;
This should help you a bit!
import java.text.DecimalFormat;
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) {
//Welcome message
String username;
double item = 0.0;
Scanner keyboard = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("Please enter your name");
username = keyboard.next();
System.out.println("Welcome to the Java Byte Code Coffee Shop," + username + "!");
//Menu
System.out.println("Here is our menu.");
System.out.println("1. Coffee $1.50");
System.out.println("2. Latte $3.50");
System.out.println("3. Cappuccino $3.25");
System.out.println("4. Expresso $2.00");
//Item selection
int item_Number = 0;
System.out.println("Please enter an item number.");
item_Number = keyboard.nextInt();
if (item_Number == 1) {
item = 1.50;
}
if (item_Number == 2) {
item = 3.50;
}
if (item_Number == 3) {
item = 3.25;
}
if (item_Number == 4) {
item = 2.00;
}
//Item Quantity
int quantity = 0;
System.out.println("Please enter the quantity.");
quantity = keyboard.nextInt();
double total = quantity * item;
System.out.println("Total before discount and tax is $ " + df.format(total));
//Discount and tax
double nuTotal;
if (total >= 10) {
nuTotal = total - (total * 0.10);
} else {
nuTotal = total;
}
System.out.println("Your total with discount is $" + df.format(nuTotal));
double totalTax = nuTotal + (nuTotal * 0.07);
System.out.println("Your total with tax is: $" + df.format(totalTax));
System.out.println("Thank you " + username + "! Please stop by again!");
}
}
I advise you to follow name patterns for the Java programming language and its variables... you could see the documentation in here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
I also suggest you to initialize your variables in order to avoid Null values while validating.
Hope this helps! It's working already... but I'm not sure what are your expectations, good luck!