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";
}
}
});
Related
I am creating a program that basically asks a user what they wish to purchase and gives them their total.
I am supposed to use 2 separate methods outside of Main to complete this task:
One method to get the user input as to which service they want performed, this method will also tell the user the total cost of the services (BEFORE TAX AND LABOR)
Another method to calculate labor costs and tax costs
The first method should return total cost to the main method, and the second method should get that total from the main method and calculate the Final Cost after labor and tax are added in.
(if the car is an import, 5% of the total should be added on)
Here is what I have so far:
import java.util.Scanner;
public class Assign3 {
public static double carMaintenance(String userCar) {
Scanner input = new Scanner(System.in);
String service_ordered="";
String more="yes";
double amount;
double total=0;
//declare and intialize parallel arrays, Services and Prices and display them to the user
String[] services = {"Oil Change" , "Tire Rotation", "Air Filter", "Fluid Check"}; //intialize list of services
double[]price = {39.99, 49.99, 19.99, 10.99}; //initialize corresponding price for services
for(int i= 0; i < services.length; i++) {
System.out.print( services[i]+ "...." );
System.out.print( price[i] + "\t");
}
do // *****2. THIS IS WHAT IS BEING EXECUTED FROM THE METHOD CALL IN MAIN *****
{
System.out.print("What service do you want done?: ");
String choice = input.nextLine();
if (choice.equalsIgnoreCase("oil change")) {
System.out.println("You chose an oil change");
amount = 39.99;
total = total + amount;
service_ordered+="Oil Change ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
} else if (choice.equalsIgnoreCase("tire rotation")) {
System.out.println("You chose a tire rotation");
amount = 49.99;
total = total + amount;
service_ordered+="Tire Rotation ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
} else if (choice.equalsIgnoreCase("air filter")) {
System.out.println("You chose an air filter");
amount = 19.99;
total = total + amount;
service_ordered+="Air Filter ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
} else if (choice.equalsIgnoreCase("fluid check")) {
System.out.println("You chose a flud check");
amount = 10.99;
total = total + amount;
service_ordered+="Fluid Check ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
}
} while (more.equalsIgnoreCase("yes"));
System.out.println("You ordered: " + service_ordered);
System.out.println("Your total due is " + total);
return total;
}
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.println("What kind of car do you have?: "); //****1. CODE STARTS HERE *****
String userCar = input.nextLine();
double total = carMaintenance(userCar); //*****2. CODE CALLS THIS METHOD AND EXECUTES IT *****
calcFinalPrice(total);
}
public static void calcFinalPrice(double total) {
double salesTax=.08;
double laborFee=.3;
double importFee=.05;
Scanner input = new Scanner(System.in);
System.out.println("Is your vehicle an import?: ");
String isImport = input.nextLine();
if(isImport.equals("yes")) {
total=total*laborFee+total; // this is the labor fee
double importTotal = total*importFee+total;
double totalAfterTax = importTotal*salesTax+importTotal; //this is the import total aftertax
System.out.println("It will cost " + totalAfterTax + " to fix your vehicle.");
}
if(isImport.equals("no")) {
total=total*laborFee+total; // this is the labor fee
double totalAfterTax = total*salesTax+total; //this is the total aftertax
System.out.println("It will cost " + totalAfterTax + " to fix your vehicle ");
}
}
}
I'm creating a program which prints a summary of the situation after interactive input has ended (ctrl - d). So it prints a summary of the average age and percentage of children who have received vaccines after interactive input.
However, I'm always receiving the No Line Found error whenever I press ctrl-d at Name:. My compiler tells me the error is at name = sc.nextLine(); within the while loop but I don't know what is causing the error exactly.
public static void main(String[] args) {
String name = new String();
int age, num = 0, i, totalAge = 0;
boolean vaccinated;
int numVaccinated = 0;
double average = 0, percent = 0, count = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
while(sc.hasNextLine())
{
sc.nextLine();
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
}
average = (double) totalAge/num;
percent = (double) count/num * 100;
System.out.printf("Average age is %.2f\n", average);
System.out.printf("Percentage of children vaccinated is %.2f%%\n", percent);
}
}
You do not correctly implement an exit condition for your loop if you ask me.
Try something like this:
String input = "";
do {
System.out.print("Name: ");
name = sc.nextLine();
[... all your input parameters ...]
sc.nextLine();
System.out.print("Do you want to enter another child (y/n)? ");
input = sc.nextLine();
} while (!input.equals("n"));
This way you can quit entering new persons without having to enter a strange command that might lead to an error. Furthermore, a do-while loop helps you to reduce your code, because you don't have to use the same code twice, i.e., everything between Scanner sc = new Scanner(System.in); and while(sc.hasNextLine()) in your example.
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 ...
}
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("="));
This question already has answers here:
How to get average from given values
(3 answers)
Closed 9 years ago.
My program is supposed to find the average of female, male, and total average GPA of students. And also total female, male, and total students. First it asks if the student is male or female. If you choose male it does the loop, but after it ends. I want my program to go straight into the next choice. Example if you choose male the you'll input female and visa versa.
import java.util.Scanner;
public class practice {
public static void main(String [] args) {
Scanner keyboard = new Scanner (System.in);
int maleCount=0, femaleCount=0, totalStudents;
double GPA, mTotal = 0, mAverage, fTotal = 0, fAverage, allAverage;
System.out.println("Is the student Male or Female?");
System.out.println("Enter M for male or F for female.");
String student = keyboard.next().toUpperCase();
System.out.println("Enter GPA");
GPA = keyboard.nextDouble();
if (student.equals("M")) {
while (GPA >=0) {
mTotal = mTotal + GPA;
maleCount++;
GPA = keyboard.nextDouble();
}
}
if (student.equals("F")) {
while (GPA >=0) {
fTotal = fTotal + GPA;
femaleCount++;
GPA = keyboard.nextDouble();
}
}
mAverage = mTotal/maleCount;
fAverage = fTotal/femaleCount;
allAverage = mTotal + fTotal;
totalStudents = maleCount + femaleCount;
System.out.println("Total MALE students: " + maleCount);
System.out.println("Total FEMALE students: " + femaleCount);
System.out.println("Total STUDENTS: " + totalStudents);
System.out.println("Total MALE GPA: " + mTotal);
System.out.println("Total FEMALE GPA: " + fTotal);
System.out.println("Total MALE Average GPA: " + mAverage);
System.out.println("Total average: " + allAverage);
}
}
How to use loops and average in Java?
Well, pretty much as in the code in your question, I'd say. Just add a loop around the part that needs a loop, and figure out how you are going to end the looping.
The other problems that leap out at me are:
You seem to be accepting the input in a strange order.
You are calculating allAverage incorrectly. Just look at the code again. The problem should be obvious.
Actually, one of the difficulties with answering this Question is that it is not at all clear how the program as written is supposed to behave. And we can't infer that from what you've shown us. 'Cos what you've written obviously doesn't work ... from a usability perspective.
If you don't understand and can't explain the requirements properly, there is not much chance that you will be able to implement them correctly.
Fixed my code sorry for it being unclear.
import java.util.Scanner;
public class practice
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner (System.in);
int maleCount=0, femaleCount=0, totalStudents, count = 0;
double GPA, mTotal = 0, mAverage, fTotal = 0, fAverage, allAverage;
System.out.println("Is the student Male or Female?");
System.out.println("Enter M for male or F for female.");
String student = keyboard.next().toUpperCase();
do{
System.out.println("Enter GPA " + student);
GPA = keyboard.nextDouble();
if (student.equals("M"))
{
while (GPA >=0)
{
mTotal = mTotal + GPA;
maleCount++;
GPA = keyboard.nextDouble();
}
student = "F";
}
else if (student.equals("F"))
{
while (GPA >=0)
{
fTotal = fTotal + GPA;
femaleCount++;
GPA = keyboard.nextDouble();
}
student = "M";
}
}
while (++count < 2);
mAverage = mTotal/maleCount;
fAverage = fTotal/femaleCount;
totalStudents = maleCount + femaleCount;
allAverage = (mTotal + fTotal)/totalStudents;
System.out.println("Total MALE students: " + maleCount);
System.out.println("Total FEMALE students: " + femaleCount);
System.out.println("Total STUDENTS: " + totalStudents);
System.out.println("Total MALE GPA: " + mTotal);
System.out.println("Total FEMALE GPA: " + fTotal);
System.out.println("Total average: " + allAverage);
}