Type " = " and get result - java

as soon as I press enter after typing the expression,it displays result which is calculate grossProfit, Studio and Theater. And now I want that it should wait for me to type "=" and then show the result? can some one help me how to type "=" and then show the result? Thanks
package ticket;
import java.util.Scanner;
import java.text.NumberFormat;
public class Ticket {
public static void main(String[] args) {
//----------------------------------------------
//calculate grossProfit, Studio and Theater.
//------------------------------------------------
final double TICKETPRICE=8, PROFITERATE=.25;
int numberofticket;
double grossProfit,theater,studio;
String replace;
String name = "name";
NumberFormat fmtCur = NumberFormat.getCurrencyInstance();
NumberFormat fmtPct = NumberFormat.getPercentInstance();
Scanner scan = new Scanner(System.in);
System.out.print("Enter movie name:");
name = scan.nextLine();
System.out.print("Enter tickets....");
numberofticket= scan.nextInt();
replace = name.replace ('a', 'A');
grossProfit = TICKETPRICE * numberofticket;
theater = grossProfit * PROFITERATE;
studio = grossProfit - theater;
System.out.println("Box Office Report");
System.out.println("Movie Name =" + replace);
System.out.println("Tickets =" + numberofticket);
System.out.println("TICKETPRICE =" +fmtCur.format(TICKETPRICE));
System.out.println ("grossProfit= " + fmtCur.format(grossProfit));
System.out.println ("theater = " + fmtCur.format(theater) + " at " + fmtPct.format(PROFITERATE));
System.out.println ("studio = " + fmtCur.format(studio));
}
}

Just ask user a line before printline like:
do {
//message for user to add line?
String nextLine = scan.nextLine();
while (!nextLine.equals("="));

Related

I got "Operator '*' cannot be applied to 'java.lang.String', 'double'" on the 4th from bottom line. Any fixes? Thanks

Below is code :
import java.util.Scanner;
public class Lab_04_01_SalesTax
{
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("What was the price of your purchase?");
String price = myObj.nextLine();
System.out.println("Price is: $" + price + " before tax.");
int totalPrice = price * .05;
System.out.println("Total price is: $" + totalPrice);
}
}

I have a program where i would like to validate user input in java i want the user to input a double value and only a double value any suggestions?

I did what i could and now the code works however when the user inputs the wrong value and is prompted to try again you have to hit enter and then you are asked to input a value, i cant think of what it is.
i also want to be able to get the program to start again after completing, i tried a do, while loop but it looped infinitely
public static void main(String[] args) {
String nameOfIngredient = null;
Float numberOfCups = null;
Float numberOfCaloriesPerCup = null;
Float totalCalories;
while(nameOfIngredient == null)
{nameOfIngredient = setIngredients(); }// Allows us to loop
while(numberOfCups == null)
{numberOfCups = setNumberOfCups(); }// Allows us too loop
while(numberOfCaloriesPerCup == null)
{numberOfCaloriesPerCup = setNumberOfCalories();} // Allows us to loop
totalCalories = numberOfCups * numberOfCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberOfCups + " cups and this amount contains " + totalCalories + " total calories.");
System.out.print("\n");
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static String setIngredients() {
System.out.println("Please enter the name of the ingredient: ");
Scanner scan = new Scanner(System.in);
try {
String ingredients = scan.nextLine();
System.out.println("\r");
return ingredients;
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCups() {
System.out.println("Please Enter Number Of Cups: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCups = scan.nextLine();
Float numberOfCupsFloat = Float.parseFloat(numberOfCups);
System.out.println("\n");
return numberOfCupsFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid Input must be a numeric value Please Try Again: ");
System.out.println("\n");
scan.nextLine();
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again.");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCalories() {
System.out.println("Please Enter Number Of Calories per cup: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCalories = scan.nextLine();
Float numberOfCaloriesFloat = Float.parseFloat(numberOfCalories);
System.out.println("\n");
return numberOfCaloriesFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid value Please enter a numeric value:");// if the input is incorrect the user gets prompted for the proper input
scan.nextLine();// if the input is incorrect the user gets prompted for the proper input
}
catch (Exception e){
scan.nextLine();
System.out.println("Error in input please try again.");
}
return null;
}
You may want to accept it as a string and check if it is numeric or not using String methods. Post that you can either move forward if format is correct or re prompt the user for correct value while showing the error.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(!numCups.chars().allMatch( Character::isDigit ))
{
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
numberCups = Double.parseDouble(numCups);
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
Alternatively you could also do this using try catch statements. I believe this would be a better way to parse double values
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(numberCups==0.0)
{
try {
numberCups = Double.parseDouble(numCups);
} catch (NumberFormatException e) {
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
}
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
I've taken your code and added support for input of fractional numbers. Comments added on important changes.
parseCups returns an Optional so we can tell if the input was valid or not.
parseIngredientValue does the work of deciding whether or not the input is a fraction and/or attempting to parse the input as a Double.
package SteppingStone;
import java.util.Optional;
import java.util.Scanner;
public class SteppingStone2_IngredientCalculator {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
String cupsStr = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); // In case ingredient is more than one word long.
Optional<Double> cups = Optional.empty();
while (cups.isEmpty()) { // repeat until we've got a value
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
cupsStr = scnr.nextLine();
cups = parseCups(cupsStr);
}
numberCups = cups.get();
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
// Using String.format to allow rounding to 2 decimal places (%2.2f)
System.out.println(String.format("%s uses %2.2f cups and this amount contains %2.2f total calories.",
nameOfIngredient, numberCups, totalCalories));
}
private static double parseIngredientValue(String input) {
if (input.contains("/")) { // it's a fraction, so do the division
String[] parts = input.trim().split("/");
double numerator = (double) Integer.parseInt(parts[0]);
double denomenator = (double) Integer.parseInt(parts[1]);
return numerator / denomenator;
} else { // it's not a fraction, just try to parse it as a double
return Double.parseDouble(input);
}
}
private static Optional<Double> parseCups(String cupsStr) {
double result = 0.0;
String input = cupsStr.trim();
String[] parts = input.split(" +"); // split on any space, so we can support "1 2/3" as an input value
switch (parts.length) {
case 2:
result += parseIngredientValue(parts[1]); // add the 2nd part if it's there note that there's no
// break here, it will always continue into the next case
case 1:
result += parseIngredientValue(parts[0]); // add the 1st part
break;
default:
System.out.println("Unable to parse " + cupsStr);
return Optional.empty();
}
return Optional.of(result);
}
}
Sample run:
Please Enter Ingredient Name:
Special Sauce
Please enter the number of cups of Special Sauce required:
2 2/3
Please enter the number of calories per cup of Special Sauce :
1500
Special Sauce uses 2.67 cups and this amount contains 4000.00 total calories.

Error: cannot find symbol compiling (elementary java)

I'm working on a programming project for my intro class. I have a code that I'm trying to compile, but I'm having a hard time getting it to work after I added the PrintWriter. All was running well until I tried to print to a text file. Can someone help me figure out how to get it to run?
(Also, if you find any errors in my logic/layout/whatever, try to contain it! I still want to debug the program myself, I just can't do that until it runs :)
Attempt: (so far)
import java.util.Scanner; //import scanner
import java.util.Random; //import randomizer
import java.io.*; //needed for throws clause
public class randomLottery
{
public static void main(String[] args) throws IOException
{
String fullName;
Scanner keyboard = new Scanner( System.in );
//so we can generate random numbers
Random rand = new Random();
//declare a constant number of numbers
final int LOTTERY_NUMBERS = 5;
//Retrieve names
System.out.print("Please enter a first and last name for lottery "
+ "entry (type 'quit' to end): ");
fullName = keyboard.nextLine();
while(!fullName.contains(" "))
{
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
while(!fullName.contains("quit"))
{
//separate first/last name
String[] parts = fullName.split(" ");
String firstName = parts[0];
String lastName = parts[1];
//Open the file
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
//Print the name onto the file
outputFile.print(lastName + ", " + firstName + ": ");
int number;
for (number = 1; number <= LOTTERY_NUMBERS; number++)
{
if (number == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.println(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
//get the next name
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
//Winning Lottery Numbers
outputFile.print("The winning numbers are: ");
int winning;
for (winning = 1; winning <= LOTTERY_NUMBERS; winning++)
{
if (winning == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
outputFile.close();
}
}
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
Should be outside (before) the while loop. Having it inside the loop means it is not in the scope of your other uses of outputFile after the while loop.

How to use variable without recalling method

My program must ask the quantity of batteries and display the quantity on the message pain. To do so I must pass the variable quantity = getQuantity so that I can display the number of batteries selected. The problem is when I do so it asks for user input "How many batteries would you like to purchase" twice. I am learning and a student so please provide help that provides better understanding. I don't simply want to fix the code I want to understand. I have played with just adding quantity and several other options but nothing seems to both display quantity of batteries selected and only ask the question once.
import javax.swing.JOptionPane;
import java.io.*;
/**
* #author Arnie
*/
public class VapeSolutions2 {
/**
* #param args
*/
public static void main(String[] args) {
// declare variables
String openingMsg, nameInputMsg, customerName, nameOutputMsg,
returnInputMsg, customerReturn, returnOutputMsg,
greetingOutputMsg, outputMsg, colorSelection, colorInputMsg, ColorOutputMsg, priceOutputMsg,
batteryOutputMsg;
int quantity;
double grandTotal;
// display opening message
openingMsg = "*** Welcome to Vape Ordering Solutions ***\n"
+ " It's a great day to order a Vape Supplies!";
JOptionPane.showMessageDialog(null, openingMsg);
// get required input using dialogs
nameInputMsg = "Please enter your name: ";
customerName = getStringInput(nameInputMsg);
returnInputMsg = "Are you a returning customer (yes or no)? ";
customerReturn = getStringInput(returnInputMsg);
colorInputMsg = "What Color would you like?";
colorSelection = getStringInput(colorInputMsg);
grandTotal = totalCost();
quantity = getQuantity();
// build output strings
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
greetingOutputMsg = "Thank you for ordering from Vape Ordering Solutions!" + "\n\n"
+ "Your order will be shipped the following day" + ".\n";
ColorOutputMsg = "Your Color selected is " + colorSelection + ".\n";
batteryOutputMsg = "Total Batteries Ordered is" + quantity + ".\n";
priceOutputMsg = "Your total purchase price is $" + grandTotal + "\n";
// create and display output string
outputMsg = nameOutputMsg + returnOutputMsg + greetingOutputMsg + ColorOutputMsg + batteryOutputMsg
+ priceOutputMsg;
JOptionPane.showMessageDialog(null, outputMsg);
System.exit(0);
} // end main()
private static String getStringInput(String prompt) {
String input;
input= JOptionPane.showInputDialog(prompt);
int i = 0;
while (input.length() == 0 && i < 3){
JOptionPane.showInputDialog("Please enter a valid value\n"+ prompt);
i++;
if (i == 3){
JOptionPane.showMessageDialog(null,"You have exceeded the maximum attempts to input correct data");
System.exit(0);
}
}
return input;
}
private static int getQuantity( ){
int quantity;
String quantityMsg = "How many batteries would you like to order?";
String quant = getStringInput (quantityMsg);
quantity = Integer.parseInt(quant);
return quantity;
}
// total = grandTotal (quantity, 5,.07)
private static double totalCost( ) {
int number;
double cost, salesTaxRate, tax, grandTotal, subTotal;
cost = (20.00);
number = getQuantity ();
salesTaxRate = (.07);
subTotal = number * cost;
tax = subTotal * salesTaxRate;
grandTotal = subTotal + tax;
return grandTotal;
}
} // end class VapeSolutions2
try with:
quantity = getQuantity();
grandTotal = totalCost(quantity);
and update your method "totalCost":
// total = grandTotal (quantity, 5,.07)
private static double totalCost( int quantity) {
//code ...
number = quantity;
//code ...
}

combo box does not work properly [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have here a simple ordering system which requires the user to input cashier name, customer name and password. After the user completes that process it will then show a combo box that contains different meals.
What I want to happen is that once I clicked a meal, it should display the name of the meal I selected and should perform the action I declared in the actionlistener.
The program compiles fine but the logic I want to happen isn't working, I'm trying my best to fix this but I think I can't do this on my own please help me thanks!
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SubokUlit {
private JComboBox combo;
private String a = "";
private static int answer;
private static int total = 0;
private static int total1 = 0;
private static int wew = 0;
private static String order1 = "";
private static String order2 = "";
private static Scanner inp = new Scanner(System.in);
public SubokUlit(){
String mgaPagkainTo[] = {"PM1 (Paa/ Spicy Paa with Thigh part)","PM2 (Pecho)"};
JFrame frame = new JFrame("Mang Inasal Ordering System");
JPanel panel = new JPanel();
combo = new JComboBox(mgaPagkainTo);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
panel.add(combo);
frame.add(panel);
combo.addActionListener(new ActionListener(){ // The logic in here does not work
public void actionPerformed(ActionEvent e){
String str = (String)combo.getSelectedItem();
a = str;
if(a.equals("PM1 (Paa/ Spicy Paa with Thigh part)")){ // If I select PM1 in the combo box it should do the following. But it doesn't work
System.out.print ("\n\n\n\t\tYou have chosen Paborito Meal 1.\n");
System.out.print ("\t\t\tPlease enter the quantity: ");
int quantity1 = inp.nextInt();
total = quantity1 * 99;
order1 = quantity1 + " " + "PM1 " + " " + total +"\n";
}
else if(a.equals("PM2 (Pecho)")){ // The same thing should alaso happen here in PM2
System.out.print ("\n\n\n\t\tYou have chosen Paborito Meal 2.\n");
System.out.print ("\t\t\tPlease enter the quantity: ");
int quantity2 = inp.nextInt();
total1 = quantity2 * 99;
order2 = quantity2 + " " + "PM2 " + " " + total1 +"\n";
}
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,100);
frame.setVisible(true);
}
public static void main(String[]args) {
Scanner inp = new Scanner(System.in);
String userNamePoe = "";
String customerNamePoe = "";
String sanKaKain = "";
boolean ulitinMoPows = true;
boolean tryAgain = true;
System.out.print("\nInput Customer Name: ");
String customerName = inp.nextLine();
customerNamePoe = customerName;
System.out.print("\nInput Cashier Name: ");
String user = inp.nextLine();
userNamePoe = user;
do{
System.out.print("\nInput either Dine In or Take Out: ");
String dInDOut = inp.nextLine();
sanKaKain = dInDOut;
if (sanKaKain.equals("Dine In") || sanKaKain.equals("Take Out")){
System.out.print("");
ulitinMoPows = false;
}
else{
JOptionPane.showMessageDialog(null, "Try again! Please input Dine In or Take Out only!","Error", JOptionPane.ERROR_MESSAGE);
ulitinMoPows = true;
System.out.print ("\f");
}
}while(ulitinMoPows);
do{
System.out.print("\nInput password: ");
String pass = inp.nextLine();
if(pass.equals("admin")){
System.out.print("");
tryAgain = false;
}
if(!pass.equals("admin")){
JOptionPane.showMessageDialog(null, "Try again! Invalid password!","Error Logging-In", JOptionPane.ERROR_MESSAGE);
tryAgain = true;
System.out.print ("\f");
}
}while(tryAgain);
System.out.print("\n\n\t\tCashier: " +userNamePoe);
System.out.print(" "+sanKaKain);
System.out.print("\n\t\tCustomer Name: " +customerNamePoe);
SubokUlit j = new SubokUlit(); //Supposedly, once the selecting of meal is done, it should now go to the next part wherein the total bill will display and asks the user how much is his cash.
int lahatNgOrderMo = total + total1;
double multiplierVat = 0.12;
double vatCollected = lahatNgOrderMo * multiplierVat;
System.out.print("\n\n\tYour total bill is: "+lahatNgOrderMo); // Displays the bill
System.out.print("\n\tCash Tendered: "); // Asks the user how much is his cash
double cashTendered = inp.nextInt();
double sukliMo = cashTendered - lahatNgOrderMo;
System.out.print("\n\n\t\t MANG INASAL");
System.out.print("\n\t\t BLUMENTRITT BRANCH");
System.out.print("\n\t\t #1631-1633 BLUMENTRITT ST.,");
System.out.print("\n\t\t STA CRUZ. MANILA 0000");
System.out.print("\n\t\t (932) 885-5844\n");
System.out.print("\n\t\t Operated by: R L YU");
System.out.print("\n\t\t TIN 202-161-017-000 VAT");
System.out.print("\n\t\t ACC. NO.: 050-204079836-000019");
System.out.print("\n\t\t Tel. #: (02)493-6801");
System.out.print("\n\n\t\tCashier: " +userNamePoe);
System.out.print("\t\t STATION: 2");
System.out.print("\n\t\t---------------------------------------------");
System.out.print("\n\t\tO.R #: 84486");
System.out.print(" "+sanKaKain);
System.out.print("\t\t\n Customer Name: " +customerNamePoe);
System.out.print(" 24");
System.out.print("\n\t\t---------------------------------------------");
System.out.print("\n\t\t >>SETTLED<<\n\n");
System.out.print(""+order1);
System.out.print(""+order2);
System.out.print("\n\n\t\tSUB TOTAL: "+lahatNgOrderMo);
System.out.print("\n\t\tDELIVERY VAT: 0.00");
System.out.print("\n\t\t ======");
System.out.print("\n\t\tAMOUNT DUE: "+lahatNgOrderMo);
System.out.print("\n\n\t\tVAT 12% COLLECTED "+vatCollected);
System.out.print("\n\n\t\tCASH Tendered: "+cashTendered);
System.out.print("\n\t\t ======");
System.out.print("\n\t\tCHANGE: "+sukliMo);
System.out.print("\n\t\t >>Ticket #: 62<<");
System.out.print("\n\t\t Created: ");
System.out.print("\n\t\t SETTLED: ");
System.out.print("\n\n\t\t*********************************************");
System.out.print("\n\t\tTHIS SERVES AS AN OFFICIAL RECEIPT.");
System.out.print("\n\n\t\tFor Feedback: TEXT MIO467(Comments/ Suggest");
System.out.print("\n\t\tions) and SEND to 0917-5941111 or CALL US");
System.out.print("\n\t\tat 0917-5596258");
System.out.print("\n\t\tEmail: feedback#manginasal.com");
System.out.print("\n\n\t\t THANK YOU FOR DINING WITH US!");
System.out.print("\n\n\t\t*********************************************");
System.out.print("\n\t\tS/N: 120416ASL03/1105-6105-9230");
System.out.print("\n\t\tDT S/N: 41-L6971 (P0S1)");
System.out.print("\n\t\tPERMIT NO: 0412-031-125295-000");
System.out.print("\n\t\tMIN: 120276752");
}
}
You have to make sure an eventlistener is attached to your JComboBox, so the application knows what to do when something happens.
In this case, you want to attach an ItemListener().
You can use something like this:
combo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
System.out.println("Meal chosen: " + combo.getSelectedItem().toString());
String optionalParameter = combo.getSelectedItem().toString();
DoMethodWhatYouNeedToDoWhenYouSelectedSomething(optionalParameter);
}
});
EDIT: Your code should be like this:
combo.addActionListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e){
String str = (String)combo.getSelectedItem();
a = str;
if(a.equals("PM1 (Paa/ Spicy Paa with Thigh part)")){
System.out.print ("\n\n\n\t\tYou have chosen Paborito Meal 1.\n");
System.out.print ("\t\t\tPlease enter the quantity: ");
int quantity1 = inp.nextInt();
total = quantity1 * 99;
order1 = quantity1 + " " + "PM1 " + " " + total +"\n";
}
else if(a.equals("PM2 (Pecho)")){
System.out.print ("\n\n\n\t\tYou have chosen Paborito Meal 2.\n");
System.out.print ("\t\t\tPlease enter the quantity: ");
int quantity2 = inp.nextInt();
total1 = quantity2 * 99;
order2 = quantity2 + " " + "PM2 " + " " + total1 +"\n";
}
}
});

Categories