I am just learning how to use switch statements. I am trying to create a shopping cart of items sold at a grocery store. I have to create a program that adds the values of the items sold and then print the final value. This is what I have so far but when I terminate my program I get an error and it doesn't display the final value.
Any help is much appreciated!!
package Exercises;
import java.util.Scanner;
public class CalculatingSales {
public static void main(String[] args)
{
int total = 0;
int prod1Count = 0, prod2Count = 0, prod3Count = 0, prod4Count = 0, prod5Count = 0;
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n %s%n %s%n %s%n","Enter product number sold: " //prompt user to enter input
,"NOTE: Product number must be between 1 & 5",
"To terminate input... ",
"On UNIX/Linus?mac OS X type <Ctrl> d then press Enter",
"On Windows type <Ctrl> z then press Enter");
while(input.hasNext())
{
int item = input.nextInt();
total =+ item;
double product1;
double product2;
double product3;
double product4;
double product5;
switch (item + total)
{
case 1:
product1 = 2.98;
++prod1Count;
break;
case 2:
product2 = 4.50;
++prod2Count;
break;
case 3:
product3 = 9.98;
++prod3Count;
break;
case 4:
product4 = 4.49;
++prod4Count;
break;
case 5:
product5 = 6.87;
++prod5Count;
break;
default:
System.out.println("ERROR. You did not enter a value between 1 & 5!");
break;
}//end switch
}//end while
double shoppingCart = (double) total;
System.out.printf("%nTotal retail value of all products is: $%d", shoppingCart);
}
}
The problem is here:
System.out.printf("%nTotal retail value of all products is: $%d", shoppingCart);
The printf is expecting an int but you are passing an double as an argument.
Try this:
System.out.printf("%nTotal retail value of all products is: $%.2f", shoppingCart);
Also you should change total =+ item; to total += item;
There are a number of problems with the code. The error at the end is because you are trying to output a double and specifying an integer to print. $%d should be $%f however to make money display to two decimal places you can use $%.2f. More information on formatting can be found in this documentation
The major problems though are in your loop. The switch statement should only be passed the item number you want to compare to and do something accordingly.So the switch simply has to be switch (item) . There is a simpler way to do the total and do the switch. You can keep a running total by adding to it the value of the product the person selected each time through the loop. Upon exiting it should be the total amount for all the items selected. If you enter an item out of range it effectively adds 0.
At the end you really should close the scanner to do proper cleanup so input.close() would be a good idea as well.
The code could look something like:
package Exercises;
import java.util.Scanner;
public class CalculatingSales {
public static void main(String[] args)
{
double total = 0.0;
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n %s%n %s%n %s%n","Enter product number sold: " //prompt user to enter input
,"NOTE: Product number must be between 1 & 5",
"To terminate input... ",
"On UNIX/Linus?mac OS X type <Ctrl> d then press Enter",
"On Windows type <Ctrl> z then press Enter");
while(input.hasNext())
{
double prodvalue = 0.0;
int item = input.nextInt();
switch (item)
{
case 1:
prodvalue = 2.98;
break;
case 2:
prodvalue = 4.50;
break;
case 3:
prodvalue = 9.98;
break;
case 4:
prodvalue = 4.49;
break;
case 5:
prodvalue = 6.87;
break;
default:
System.out.println("ERROR. You did not enter a value between 1 & 5!");
break;
}//end switch
total += prodvalue;
}//end while
double shoppingCart = total;
System.out.printf("%nTotal retail value of all products is: $%.2f", shoppingCart);
input.close();
}
}
There are much better ways of doing this but as time goes on you will probably learn how this program could be simplified. I wanted to keep the code somewhat structured the way you seemed to be handling things.
If you need the counts of each individual item then you will have to modify the code above to add them back in. I realize this solution may have oversimplified what you needed but at a basic level it keeps the overall total right.
Related
I'm currently trying an example from my textbook on learning java, but my code after an EoF statement just gets ignored by the compiler.
package lettergrades;
import java.util.Scanner;
public class LetterGrades {
public static void main(String[] args) {
int total = 0;
int gradeCounter = 0;
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n %s%n %s%n", "Enter the integer grades in the range 0-100", "Type the end-of-file indicator to terminate input", "on unix type <ctrl> d then press Enter","On windows type <Ctrl> z then press enter");
while (input.hasNext()){
int grade = input.nextInt();
total += grade;
++gradeCounter;
switch (grade/10){
case 9:
case 10:
++aCount;
break;
case 8:
++bCount;
break;
case 7:
++cCount;
break;
case 6:
++dCount;
break;
default:
++fCount;
break;
}
}
System.out.printf("%nGrade Report:%n");
if (gradeCounter !=0){
double average = (double) total/gradeCounter;
System.out.printf("total of the %d grades entered is %d%n", gradeCounter, total);
System.out.printf("Class average is %.2f%n", average);
System.out.printf("%n%s%n%s%d%n%s%d%n%s%d%n%s%d%n%s%d%n", "Number of students that received each grade","A: ", aCount, "B: ", bCount , "C: ", cCount, "D: ", dCount, "F: ", fCount);
}
else
System.out.println("No grades were entered");
}
}
This is the output i get :
Enter the integer grades in the range 0-100
Type the end-of-file indicator to terminate input
on unix type <ctrl> d then press Enter
On windows type <Ctrl> z then press enter
But when i input ctrl D and press enter, nothing happens. Why don't the printf and if statements work?
As e.g. #FredLarson is reporting, it's working fine for most. You're relying on EOF character resulting in sysin being closed, which will in turn cause scanner's hasNext() to return false.
Evidently, on your system, that isn't working. If you're running this inside an IDE's 'console', they often don't let you close sysin or work differently from the command line.
You can try to figure out which voodoo key combo ends things, but there is an alternative.
Instead of EOF, or in addition to EOF, make another symbol that ends inputs. Perhaps 0, or 'END'. In the later case you can no longer rely on nextInt, you'd have to call next, check if it is END, if yes, stop accepting input, and if not, toss it through Integer.parseInt to end up with a numeric value.
Now you no longer have to mention various platforms in your console messages, and you avoid these issues.
I've got to complete a current assignment that I've been making some changes to and I am stuck on what I hope will be my last problem before submission
I need to create a simple ticketing system for a cinema, and I have been able to create (with the help of other experienced developers) a working system. However, the ticketing system needs to prompt the user for confirmation to continue the method, and to show a current total cost. The confirmation needs to be the user entering the number 1, if not, to output an error message.
I've attempted using the again = br.readLine(); to output the 1 to confirm the purchase, I have also tried importing the java.util.Scanner class to then input and use int to create an error message but it continues to show errors.
package ticketingsystem;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ticketingsystem {
enum TicketType {
// I chose to use the enum class for the ticket prices, //
// as it made it much easier to use a switch statement, instead of multiple if statements. //
CHILD(18), ADULT(36), SENIOR(32.5);
//Enum classes are needed to be used in upper case, otherwise the program will crash//
//as I discovered//
TicketType(double price) {
this.price = price;
}
private double price;
public double getPrice() {
return price;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//As the program needed the ability to run in an indefinite loop constantly adding //
//calculations, I chose to use buffered reader, as it buffered the method each loop//
//continuing to add a total number.//
String type, again;
int quantity = 0;
// This is where the new calculation starts, it is set at 0 before being calculated and
//added to the total price.//
double totalPrice = 0;
TicketType ticketType;
//We link the TicketType calculations to the enum class, hence//
// TicketType ticketType.//
System.out.println("Welcome to the cinemas!");
System.out.println("MAIN MENU\n");
System.out.println("Cinema has the following ticketing options\n");
System.out.println("1 = Child (4-5 yrs)");
System.out.println("2 = Adult (18+ yrs)");
System.out.println("3 = Senior (60+ yrs)");
do {
//Our loop calculation method starts here//
System.out.print("\nEnter your option: ");
type = br.readLine();
switch (type.toLowerCase()) {
case "1":
ticketType = TicketType.CHILD;
break;
case "2":
ticketType = TicketType.ADULT;
break;
default:
ticketType = TicketType.SENIOR;
break;
}
System.out.print("Enter total No of tickets: ");
quantity = Integer.parseInt(br.readLine());
totalPrice += ticketType.getPrice() * quantity;
//totalPrice is the ticketType cost (hence the += operator), times//
//the quantity.//
System.out.printf("--> You are purchasing %s - %s Ticket(s) at $%s\n", quantity, ticketType, ticketType.getPrice());
System.out.println("Press 1 to confirm purchase");
//This is where we confirm the purchase//
// This is where the current total cost needs to be output //
System.out.print("\nDo you wish to continue? (Y/N) : ");
again = br.readLine();
} while (again.equalsIgnoreCase("y"));
//This is where the calculation method ends (as we are using a do/while loop).//
// The while statement means that if we type "y", the loop will begin again with a buffer.//
//If we type N, the loop will end, and the program will continue running past the loop.//
System.out.printf("\n==> Total Price : $%s \n", totalPrice);
}
}
If you want the user to have to press 1 to accept purchase, then just put in a simple if...else after asking that question. Something like:
String confirmation = br.readLine();
if (confirmation.equals("1")) {
totalPrice += ticketType.getPrice() * quantity;
System.out.println("Current total is: " + totalPrice);
} else {
System.out.println("You did not press 1 so ticket purchase cancelled");
System.out.println("Current cost is still: " + totalPrice);
}
So this way it will only update the total if they press 1.
Example
Newbie to Java; I've created a Command line calculator that gets a double from user and gets one operation symbol and gets another double from user and the calculates the amount.
This is my code.
import java.util.Scanner;
public class forthProblem {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double numb1, numb2, add, subtract, multiply, divide;
char operation;
while (true) {
System.out.println("Calculate: ");
numb1 = in.nextDouble();
operation = in.next().charAt(0);
numb2 = in.nextDouble();
switch (operation) {
case '+':
add = numb1 + numb2;
System.out.println(add);
break;
case '-':
subtract = numb1 - numb2;
System.out.println(subtract);
break;
case '*':
multiply = numb1 * numb2;
System.out.println(multiply);
break;
case '/':
divide = numb1 / numb2;
System.out.println(divide);
break;
}
}
}
}
What I want to figure out is how to be able to get multiple numbers from users and do multiple operations.
for example a user could type (3+4)*4/6= and get an answer.
Also I would like to implement the bedmas in the new code.
I'll appreciate your guidance.
In order to implement PEMDAS and do multiple operations, you will need to keep all input until the user sends in '='. One way to do this is reverse polish notation. Just transform the string to RPN and then run through the equation.
I'm having a problem with this program i'm trying to write for my homework. Here's the problem and the code I wrote:
A mail-order house sells five products whose retail prices are as
follows :
Product 1: $2.98, Product 2: $4.50, Product 3: $9.98, Product 4: $4.49 and
Product 5: $6.87. Write an application that reads a series of pairs of numbers as
follows:
A.
product number
B.
quantity sold
Your program should use
switch
statement to determine the retail price for each
product. It should calculate and display the total retail value of all products sold.
Use a sentinel-controlled loop to determine when the program should stop
looping and display the final results.
import java.util.Scanner;
public class Program5
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double totalCost1 = 0, totalCost2 = 0, totalCost3 = 0, totalCost4 = 0, totalCost5 = 0;
System.out.println("Please enter the product number 1-5. Enter 0 to stop. :");
int productNumber=keyboard.nextInt();
while(productNumber!=0)
{
switch (productNumber)
{
case 1:
System.out.println("Enter quantity sold :");
double product1=keyboard.nextDouble();
totalCost1 = (2.98*product1);
break;
case 2:
System.out.println("Enter quantity sold :");
double product2=keyboard.nextDouble();
totalCost2 = (4.50*product2);
break;
case 3:
System.out.println("Enter Quantity sold :");
double product3=keyboard.nextDouble();
totalCost3 = (9.98*product3);
break;
case 4:
System.out.println("Enter Quantity sold :");
double product4=keyboard.nextDouble();
totalCost4 = (4.49*product4);
break;
case 5:
System.out.println("Enter Quantity sold :");
double product5=keyboard.nextDouble();
totalCost5 = (6.87*product5);
break;
}
}
System.out.printf("Product 1: %.2f%nProduct 2: %.2f%nProduct 3: %.2f%nProduct 4: %.2f%nProduct 5: %.2f%n", totalCost1, totalCost2, totalCost3, totalCost4, totalCost5);
}
}
When I run this code, it asks to enter the product number. After I enter any number 1-5, it asks for the quantity sold. When I give any number, it keeps asking for quantity sold over and over, what did I do wrong?
You have two problems in your code:
1) No default case
2) You need to ask the user inside loop again to enter 0 to exit the
loop:
So,
1) Add default: break; inside switch
2) Add below code after the switch statement:
System.out.println("Please enter the product number 1-5. Enter 0 to stop. :");
productNumber=keyboard.nextInt();
Do you need looping until get all products? If you need only 1 product you can remove the following loop
while(productNumber!=0)
If you can get multiple products add the following line after switch statement to get next product:
productNumber=keyboard.nextInt();
After looking up numerous ways to restart a Java program within itself, a while loop seemed like the easiest option. Here's an example of a basic calculator program I'm trying this with:
import java.util.Scanner;
class a {
public static void main(String args[]){
boolean done = false;
int oper;
Scanner input = new Scanner(System.in);
System.out.println("McMackins Calc v2.0 (Now with fewer crashes!)");
while (!done)
{
System.out.println("What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
oper = input.nextInt();
switch (oper){
case 0:
done = true;
break;
case 1:
add addObject = new add();
addObject.getSum();
break;
case 2:
sub subObject = new sub();
subObject.getDifference();
break;
case 3:
times multObject = new times();
multObject.getProduct();
break;
case 4:
divide divObject = new divide();
divObject.getQuotient();
break;
case 5:
remain remObject = new remain();
remObject.getRemainder();
break;
case 6:
avg avgObject = new avg();
avgObject.getAvg();
break;
case 7:
interest intObject = new interest();
intObject.getInterest();
break;
default:
System.out.println("Invalid entry.");
break;
}
}
input.close();
}
}
However, this seems to throw out a NoSuchElementException at the end of the first time through the loop, and crashes the program. The function of this class is to take the initial input from the user to determine which class to use, which will determine which mathematical operation to perform. Everything works fine without the while (!done) loop.
Example usage:
McMackins Calc v2.0 (Now with fewer crashes!)
What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):
1
How many addends?
1
Enter your numbers now.
1
You have entered 1 addend.
The sum is: 1.0
What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):
Enter a valid integer.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at a.main(a.java:13)
I've also tried just having the other classes refer back to this one, but since main is a static method, I cannot access it the way I intended.
Note that I'm a bit of a beginner at Java, which is why my program is pretty simple, so try to keep it simple if it can be, or post code and then in DETAIL explain what it means so I can not only fix this problem, but future ones as well.
Thank you!
EDIT:
The code is formatted better within my editor. The braces came out in odd positions when I posted it here.
Since apparently a is written correctly, this is my add class. Hopefully this will clear something up.
import java.util.Scanner;
public class add {
public void getSum(){
Scanner input = new Scanner(System.in);
double total, addend;
int entries, count;
total = 0;
count = 0;
System.out.println("How many addends?");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
entries = input.nextInt();
System.out.println("Enter your numbers now.");
while (count < entries){
while (!input.hasNextDouble()){
System.out.println("Enter a valid number.");
input.next();
}
addend = input.nextDouble();
total = total + addend;
count++;
if (count == 1){
System.out.println("You have entered " + count + " addend.");
}else if (count > entries){
System.out.println("You have entered too many addends! Contact program developer.");
}else{
System.out.println("You have entered " + count + " addends.");
}
}
System.out.println("The sum is: " + total);
input.close();
}
}
public static void main(String args[]){
boolean done = false;
int oper;
Scanner input = new Scanner(System.in);
System.out.println("McMackins Calc v2.0 (Now with fewer crashes!)");
while (!done) {
System.out.println("What operation? (0 for quit, 1 for add, 2 for subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6 for average, 7 for account interest):");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
oper = input.nextInt();
switch (oper){
case 0:
done = true;
break;
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
case 3:
System.out.println("3");
break;
case 4:
System.out.println("4");
break;
case 5:
System.out.println("5");
break;
case 6:
System.out.println("6");
break;
case 7:
System.out.println("7");
break;
default:
System.out.println("Invalid entry.");
break;
}
}
input.close();
}
This seemed to work for me so perhaps the error is something to do with your own classes (add, divide) etc.
Also, it's best to keep with convention when creating your own classes by capitalizing the first letter e.g. "add" should be "Add".
You could probably make this a little bit easier to read by building a general "Operations" class which holds an add method, a subtract method etc.
EDIT:
try this for your add method:
public static int add() {
Scanner s = new Scanner(System.in);
int counter = 0;
System.out.println("How many numbers to add?");
int numCount = s.nextInt();
for(int i = 0; i < numCount; i++) {
System.out.println("enter number");
counter += s.nextInt();
}
return counter;
}
Use bufferedreader and inputstream instead of Scanner class. This class creates a lot of bugs and errors, since sometimes it takes more arguments, that you expect it to take.
Also:
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
Your using hasNextInt method wrong, instead of it try to make simple while loop with Boolean and input.next() should be replaced with input.nextLine().
Another thing, you should check,if user typed integer instead of string or something in the while loop and it range. If everything is okay, you should change Boolean value to true and make him go out of the while loop.
For future users who are wondering how to fix this issue, through some reprogramming, I discovered that my problem was closing the input variable BEFORE the end of the loop. By having the program restart indefinitely and only close input when done, this program works fine.
Thanks to Benjamin's response, I am currently in the process of cleaning up and shortening my code by way of for loops.