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();
Related
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
import java.io.*;
import java.util.*;
import java.lang.*;
class MenuList
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
List<String> items=new ArrayList<String>();
int y;
do
{
//String n="";
//int i=0;
System.out.println("********************");
System.out.println(" MENU");
System.out.println("********************");
System.out.println("Press 1 to Add an Array with to List : ");
System.out.println("Press 2 to Remove an Array from the List : ");
System.out.println("Press 3 to Add Array at an Index in the List : ");
System.out.println("Press 4 to Replace an Array in the List: ");
System.out.println("Press 5 to Show the Output : ");
System.out.println("Press 6 to exit");
y=sc.nextInt();
//int [] arr= new int[5];
switch(y)
{
case 1:
System.out.println("Enter the Element to be added " );
items.add(sc.next());
break;
case 2:
System.out.println("Enter the Element's postion which you want to Remove " );
items.remove(sc.nextInt());
break;
at case 3 and 4 i am getting the same error as before. input mismatch
case 3:
System.out.println("Enter the Elements postion and Element to be added : ");
items.add(sc.nextInt(),sc.next());
break;
index starts from 0 and increments. i input 4 values and then tried to
change the value at 2nd index it showed me the Input mismatch error
case 4:
System.out.println("Enter the Elements postion and Element to be replaced :");
items.set(sc.nextInt(),sc.next());
break;
case 5:
System.out.println("Values you stored are as follows : " +items );
break;
case 6 :
break;
default:
System.out.println("You Have Entered Invalid Choice ");
}
}
while(y != 6);
}
}
The first problem with adding is obvious, don't add 'n' in:
items.add(sc.next(n))
You didn't use it in next lines which is correct
I got your code working, and also a few comments:
Basically, you need to move
List<String> items=new ArrayList<String>();
outside the doloop. Instead of modifying it, you're recreating it in each iteration. And use sc.next() instead of sc.next(n) to read strings.
You need a bunch of error checking here, things blowup if any entry errors are made, and that's very easy to do (make an error).
Your display messages need improvement, instruct the user what needs to be entered in what order
My program should ask the user to enter some grades. After the input is finished, the program has to show which grade was entered how many times (or in another word, how many times each grade was entered).
For example, if the user enters grade 3 two times, thats menas total 2 students has got the grade 3. If the grade F is entered 3 times, that means 3 students has got the failing grade F, and so on....
The final output should look something like this:
Example output:
grade F= 3 students
grade 3= 2 studnets
and so on....
...........................
...........................
Now my problem is with keeping track of each grade and print them out telling how many times (also means how many students got each specific grade) each of the grade was entered. I can't come up with idea to solve it.
My code:
package studentgrade;
import java.util.*;
public class StudentGrade {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many total grade you want to enter (Depending on the total number of students)? ");
int totalStudents = input.nextInt();
String grade[] = new String[totalStudents];
//asking user to enter grade
for (int i = 0; i < totalStudents; i++) {
System.out.println("Enter grade " + (i + 1) + ": ");
System.out.println("Choose only between grade 3 and F:\n");
grade[i] = input.next();
if (grade[i] == "3") {//3 defines the only passing grade
//Store that into a variable
} else if (grade[i].equalsIgnoreCase("F")) {//F defines the failing grade
//Store that into a variable
}//else{
//System.out.println("Invalid input. Try again");
//}
}
//Now print out which grade was entered how many times
}
}
Define, at the top, a variable resembling each grade and set them to 0, and then, each time in the "if" statement, add one to the corresponding variable. variable++.
At the end, use
System.out.println("Grade 3: " + variable3);
System.out.println("Grade F: " + variableF);
Also, use .equals method to compare two strings in the if statement
If you don't need the sort of introduced values, simply create an array with your needed size n (don't see exactly what means from 3 to F).
int[] grade = new int[n];
If all inputs where numbers you can make direct:
grade[input.next()] ++;
Then, as all inputs are not int you can solve it with a switch
switch(input.next()) {
case "3":
grade[0] ++;
case "2":
grade[1] ++;
....
case "F":
grade[n-1] ++;
}
This is a good use for a Map. Right now your only storing the inputs 3 and F but if you wanted to adapt this program to have more grades this would scale perfectly and it is a clean and neat solution.
// the map to store how many times a grade was entered
private static final Map<String, Integer> gradeSumMap = new HashMap<String, Integer>();
public static void addToGradeSum(String key, int num) {
if(gradeSumMap.get(key) == null) {
gradeSumMap.put(key, num);
} else {
gradeSumMap.put(key, gradeSumMap.get(key) + num);
}
}
public static void printGradeSumMap() {
for(String key : gradeSumMap.keySet()) {
System.out.println("grade " + key + " = " + gradeSumMap.get(key));
}
}
// this needs to also be .equals or .equalsIgnoreCase
if (grade[i].equals("3")) {
addToGradeSum(grade[i], 1);
} else if (grade[i].equalsIgnoreCase("F")) {
addToGradeSum(grade[i], 1);
}
then just call printGradeSumMap() when you want to print it
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.
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.