Creating a simple sales calculator in Java code - java

I'm trying to figure out how to write this?
Write a Java program that will serve as a basic sales calculator. The program should present the user with a choice of four different products of your choosing in a simple menu. After the user selects a product by entering a character corresponding to a product, the program should prompt the user for the quantity and then calculate the Subtotal, Sales Tax Amount, and Total Sale Amount. The calculations should be performed as follows:
Subtotal = (Price * Quantity)
Sales Tax Amount = Subtotal * Sales Tax Percentage (use 6.5% for the sales tax percentage)
Total Sale Amount = Subtotal + Sales Tax Amount
Be sure to use variables to store temporary values. The program should output the product sold, quantity sold, and the calculated values for Subtotal, Sales Tax Amount, and Total Sale Amount. Your assignment submittal should include your java code which is properly commented, and the class file..
this is what i have so far and not sure if I am on the right track?
import java.util.scanner;
public class Sales //Defines the class
Public static void main (String args[]){
System.out.println("Welcome to Super Shopper");
System.out.println("1) Star Wars DVD");
System.out.println("2) X-box 360 ");
System.out.println("3) I-Pad 3");
System.out.println(“4) 2 liter Soda”);
System.out.println("5) Quit");
Scanner sc = new Scanner (System.in);
System.out.print("Please select item :");
int choice = keyword.nextInt();
Scanner number = new scanner (System.in);
System.out.print("Please select quantity :");
Int choice = quantity.nextInt();
String userInput;
}
}

Since this is a homework question, I won't be providing you with the answer to your problem, but hopefully I will be able to help you in figuring out how to structure your program, as well as explain how to use the Scanner class to gather input from the user. The rest will be up to you.
First you will need to develop the pseudo-code for your main program. Basically a flow of execution based on the events that should happen.
pseudo-code is NOT code that will compile, but is useful in figuring out the structure of a program. Here is the pseudo code for your program.
show greeting with choices.
get choice from user
if choice is valid and choice is not exit
prompt user for quantity
if quantity is valid
calculate total and show it to the user
restart program
if quantity is invalid
prompt user for a valid quantity again
if choice is valid and choice is exit
show exit message and exit program
if choice is invalid
show error message and restart program
Notice that upon successful completion of getting the total cost of a purchase, we "restart the program". If you were more advanced, this might entail calling a function, but my guess is that you are still a beginner, so doing the same thing more than once should remind you of a loop. In this case a while loop.
Thus we can rewrite this pseudocode to the following
done = false
while not done
get choice from user
if choice is valid and choice is not exit
prompt user for quantity
if quantity is valid
calculate total and show it to the user
if quantity is invalid
prompt user for a valid quantity again
if choice is valid and choice is exit
done = true
if choice is not valid
show error message
exit program
Now, notice how when the user inputs an invalid quantity (ie: Something that is not an integer > 1) we ask for a quantity AGAIN. Doing the same thing multiple times? That's right, that means we should probably use another while loop again.
For this second while loop, the basic thinking is, "keep asking the user for a quantity until we have a valid quantity". The simplest way to accomplish this, is to create a boolean variable we call haveQuantity, and loop until that value is true.
Our pseudo-code now becomes:
done = false
while not done
get choice from user
if choice is valid and choice is not exit
haveQuantity = false
while not haveQuantity
prompt user for quantity
get quantity from user
if quantity is valid
haveQuantity = true
calculate total and show it to the user
if choice is valid and choice is exit
done = true
if choice is not valid
show error message
exit program
This should be the general structure of your program. In the following section, I will show you how to properly use the scanner class to get input from the user.
public class EchoInt
{
import java.util.Scanner;
public static void main(String[] args)
{
//Declaration of variables outside the while loop
Scanner scan = new Scanner(System.in); //declaring variables outside of a loop saves space and speeds up execution as the jvm does not need to reallocate space for an object inside the loop.
boolean done = false; //this will be our conditional for the while loop
int input = -1;
while(!done) //while done is equal to false.
{
System.out.println("Please enter a positive int to echo or 0 to exit: ");
if(scan.hasNextInt()) //If the user has inputted a valid int
input = scan.nextInt(); //set the value of input to that int.
else //The scanner does not have a integer token to consume
{
/*
THIS IS IMPORTANT. If the scanner actually does have a token
which was not an int. For example if the user entered a string,
you need to consume the token to prepare to accept further tokens.
*/
if(scan.hasNext())
scan.next(); //Actually consumes the token
input = -1; //This is used to indicate that an invalid input was submitted
}
if(input == 0) //The user chose to exit the program
done = true; //set done to true to kick out of the while loop
else if(input == -1) //This means the user inputed an invalid input
System.out.println("ERROR! Try again."); //show error message
else //The user inputted valid input
System.out.println("echo: "+input); //Echo the int
}
scan.close(); //We are done, so close the scanner
System.out.println("Exiting. Goodbye!"); //Show a goodbye message
System.exit(0); //exit the program. The zero tells us we exited without errors.
}
}
Hope this helps. And feel free to ask more questions.

Stackoverflow really excels when you have a very specific question to ask. As for your requirements, you are asking the user for input thats good. But you are not mapping items to prices or quantities. You are hardcoding in the items position ie "3) I-Pad 3" which will make it harder to get the actual item name later and match it to it's price.

Related

Stuck While Loop (Java)

all!
I'm a university freshman computer science major taking a programming course. While doing a homework question, I got stuck on a certain part of my code. Please be kind, as this is my first semester and we've only been doing Java for 3 weeks.
For context, my assignment is:
"Create a program that will ask the user to enter their name and to enter the number of steps they walked in a day. Then ask them if they want to continue. If the answer is "yes" ask them to enter another number of steps walked. Ask them again if they want to continue. If they type anything besides "yes" you should end the program by telling them "goodbye, [NAME]" and the sum of the number of steps that they have entered."
For the life of me, I can not get the while loop to end. It's ignoring the condition that I (probably in an incorrect way) set.
Can you please help me and tell me what I'm doing wrong?
import java.util.Scanner;
public class StepCounter
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
final String SENTINEL = "No";
String userName = "";
String moreNum = "";
int numStep = 0;
int totalStep = 0;
boolean done = false;
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
// Prompt for the user's name
System.out.print("Please enter your name: ");
userName = in.nextLine();
while(!done)
{
// Prompt for the number of steps taken
System.out.print("Please enter the number of steps you have taken: ");
// Read the value for the number of steps
numStep = in.nextInt();
// Prompt the user if they want to continue
System.out.print("Would you like to continue? Type Yes/No: ");
// Read if they want to continue
moreNum = in2.nextLine();
// Check for the Sentinel
if(moreNum != SENTINEL)
{
// add the running total of steps to the new value of steps
totalStep += numStep;
}
else
{
done = true;
// display results
System.out.println("Goodbye, " + userName + ". The total number of steps you entered is + " + totalStep + ".");
}
}
}
}
To compare the contents of String objects you should use compareTo function.
moreNum.compareTo(SENTINEL) return 0 if they are equal.
== operator is used to check whether they are referring to same object or not.
one more issue with addition of steps, addition should be done in case of "No" entered also
Use
if(!moreNum.equals(SENTINEL))
Instead of
if(moreNum != SENTINEL)
Also, make sure to add: totalStep += numStep; into your else statement so your program will actually add the steps together.

Asking for user input twice in a while loop

I'm currently doing a java project. The project involves a database about NHL Statistics and about accessing bits of information from the database through user input. I'm using a while loop to ask for user input in multiple circumstances, such as asking for the number of penalties received, the number of goals scored, amount of points etc. I am having difficulty with one specific part, it asks the user input for which statistic they want (points, goals, assists, penalties, assists, player, club). After that, if the user types player as their choice, then the system is supposed to ask the user which players statistics they wish to see. The problem is that since I'm using a while loop after the user inputs the first time, the loop is executed and the program ends before the player can input the second time. Any help would be appreciated, here is my code:
import java.util.Scanner;
import nhlstats.NHLStatistics;
public class NhlStatisticsPart2 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("NHL statistics service");
while (true) {
System.out.println("");
System.out.print("command (points, goals, assists, penalties, player, club, quit): ");
String command = reader.nextLine();
if (command.equals("quit")) {
break;
}
if (command.equals("points")) {
NHLStatistics.sortByPoints();
NHLStatistics.top(10);
// Print the top ten players sorted by points.
} else if (command.equals("goals")) {
NHLStatistics.sortByGoals();
NHLStatistics.top(10);
// Print the top ten players sorted by goals.
} else if (command.equals("assists")) {
NHLStatistics.sortByAssists();
NHLStatistics.top(10);
// Print the top ten players sorted by assists.
} else if (command.equals("penalties")) {
NHLStatistics.sortByPenalties();
NHLStatistics.top(10);
// Print the top ten players sorted by penalties.
} else if (command.equals("player")) {
System.out.println("Which player statistics?");
NHLStatistics.searchByPlayer(command);
// Ask the user first which player's statistics are needed and then print them.
} else if (command.equals("club")) {
// Ask the user first which club's statistics are needed and then print them.
// Note: When printing statistics they should be ordered by points (so the players with the most points come first).
}
}
}
}
This is the message I receive:
command (points, goals, assists, penalties, player, club, quit): player
Which player statistics?
command (points, goals, assists, penalties, player, club, quit):
As can be seen, instead of allowing the user to enter which player's statistic they want to see, the program goes back to the previous questions without allowing for user input. Is there a way, whereby the user can answer the question (Which player statistics?) without the loop executing?
Well you need to ask the user to input the player. So you need to use the scanner to scan another value. If you do it when you are in the if condition it won't continue until the user inputs the value.
.....
} else if (command.equals("player")) {
System.out.println("Which player statistics?");
command = reader.nextLine(); //Read again from the input
NHLStatistics.searchByPlayer(command); //now use that second value
}
.......

Entering a Int while variable declared Double and vice versa in Java

Please help.
Statement needs to print:
"Please enter the insured value of your home as a whole number: "
Which is simple but if I enter a double the another statement prints that reads: "You must only enter an integer: "
That is where I'm stuck. Any way I do it I get fatal logic errors.
Here is my code starting with declared variable and skipping the in between code:
double homeInsVal = 0.0;
<other code>
System.out.printf("%nPlease enter the insured value of your home as a whole number: ");
homeInsVal = input.nextDouble();
{
if (homeInsVal >= 0.0)
{
System.out.printf("%nYou must only enter an integer: ");
homeInsVal = input.nextInt();
}
}
My logic is completely off. The reason why I declare homeInsVal as a double is because if I declare it as a Int as soon as I enter a decimal to purposely prompt the second statement I get a logic error an my code terminates but the way I currently have the code written the second prompt will print even if I enter an integer.
Please help!
Note: This is an intro Java class and while beggars can't be choosers have please explain as simple as possible. Thanks!
Not very clear as to what is the question. If you would want to check if the entered value is an integer or a Double, you can refer the below posts
How to find out if the value contained in a string is double or not
How to check if a double value has no decimal part
You want an integer, but the user can enter what they like, including letters and other rubbish. But you can be sure the user enters something, ie a String. Also, to send the data to your program, the user will press Enter, which puts newline char(S) into the buffer.
What does this all mean? It means you need something like this:
String line = input.nextLine();
try {
Integer number = Integer.parseInt(line);
} catch (NumberFormatException e) {
// input wasn't a number
}
This isn't the whole story, but hopefully you can build on it.

How to check for user input without exiting for error

I need to check the user input and ask for a correct one if the value is not a digit. However when I do this code, the program displays an error message and then crashes- it does not ask the user to give a new input. How can that be fixed? Thank you!
import java.util.Scanner;
import java.lang.Math;
public class CentimeterInch
{
public static void main (String [] args)
{
final int MAX=100, feet=12, meter=100;
final double inch=2.54;
Scanner scan = new Scanner (System.in);
System.out.println ("This program converts distances. ");
System.out.println ("Enter distance and unit (e.g. 37 1 or 100 2):");
double distance=scan.nextDouble();
if (!scan.hasNextDouble())
{
System.out.println ("please enter a numeric value");
distance=scan.nextDouble();
}
int unitType = scan.nextInt();
if (distance<0)
{
System.out.println ("Please enter a non negative distance");
}
....
Just bring the if clause before performing scan.nextDouble().
if (!scan.hasNextDouble())
{
System.out.println ("please enter a numeric value");
scan.nextLine();
distance=scan.nextDouble();
}
double distance=scan.nextDouble();
First make sure that the number to be read is a double value, then read it. You were doing the reverse
What is scan.nextLine() doing here?
Suppose the user enters abc 2. scan.hasNextDouble() checks wether the token to be read next is a double value or not. It's not, so scan.hasNextDouble() evaluates to false and the if clause gets executed. Inside the if clause, you have scan.nextLine(). It simply discards the current input from scan, thus flushing scan. If you don't do so, then scan still contains abc 2 and upon executing distance = scan.nextDouble(), the compiler issues an error.
It's better if you replace if with while. Suppose user gives wrong input. Your program checks the input and finds out that it's not a double value. The if clause if executed and the user is asked to enter a numeric value. What if the user again enters a wrong input. This time, you will get an error. Using a while loop makes your program to keep asking the user for a correct input until he enters a numeric value.

How to use multiple Input Dialogs (New to Java)

I am trying to create a program that asks a user for a sentinel value (a value to enter when they want to end the list). It then asks the user to enter numbers until they re-enter the sentinel value. It then figures out the max number in the list. I'm very new to Java, and whenever I run the program is just asks for the sentinel value then does nothing else (never pops up the second input dialog). I'm sure it's something simple that I'm doing wrong, but I can't figure it out. Thanks for any help.
import java.util.*;
import javax.swing.JOptionPane;
public class HW1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number;
int max;
int sentinel;
int count=0;
JOptionPane.showInputDialog("Please enter a sentinel value: ");
sentinel=input.nextInt();
JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" to end.");
number = input.nextInt();
max = number;
while (number!=sentinel){
count +=1;
if (number>max)
max=number;
JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" to end.");
number = input.nextInt();
}
if (count!=0){
JOptionPane.showMessageDialog(null, "The max is:" + max);
}
}
}
You are mixing the ways to input data to your program. Let's begin:
Scanner input = new Scanner(System.in);
The line above allows you to catch data in the command line from the keyboard.
JOptionPane.showInputDialog("Please enter a sentinel value: ");
This Option Pane is showing correctly, you put a value and then nothing happens. This is because your program is waiting to input something in the command line
sentinel=input.nextInt();
When your program arrives to the line above, the input.nextInt() stops the program until you put something in the command line.
The correct way should be something like this:
sentinel = Integer.parseInt(JOptionPane.showInputDialog("Please enter a sentinel value: "));
number = Integer.parseInt(JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" value to end."));
And remove:
number = input.nextInt();
sentinel=input.nextInt();
I think the confusion is this:
the JOptionPane opens with an input dialog
when the option pane closes, whatever you put there is ignored
then the code goes to this line sentinel=input.nextInt();
which waits for input from the console (e.g. you need to go back to the console, type the number there and press enter, only then the program will advance, it will block untill you do)
I would change it to something like this:
String sentinelInput = JOptionPane.showInputDialog("Please enter a sentinel value: ");
sentinel= Integer.parseInt(sentinelInput);
(repeat for all places where you expect input)
An alternative solution is
Don't use the JOptionPane, and instead just System.out.println to print the user a request for input (instead of the popup dialog). Then you can and keep the existing input.nextInt() calls to collect it.
Just note that all interaction will be in the console, without any popup dialogs (which I actually prefer in terms of user experience, and also it will be working in non GUI machines such as a linux terminal...)

Categories

Resources