I am having some trouble getting my sum function to work. I am trying to create a program that asks for a product number and a quantity using switch structure and a sentinel loop. It will run until 0 is entered. It should calculate the total number of products entered and the total value of all products entered. The quantity works just fine. It's the total value that will only work for the 1st product entered. I cannot get the sum for total to keep adding until 0 is pressed. Any help would be greatly appreciated!!
import java.util.Scanner;
public class Mailorder {
public static void main(String[] args) {
//create a scanner
Scanner input = new Scanner(System.in);
//declare variables
double product1 = 3.75;
double product2 = 5.95;
double product3 = 8.75;
double product4 = 6.92;
double product5 = 8.75;
double product6 = 7.87;
double total = 0.00;
//read in product #
System.out.print("Enter a product number: ");
int product = input.nextInt();
//read in quantity sold
System.out.print("Enter quantity sold for 1 day: ");
int quantity = input.nextInt();
//switch case
switch (product)
{
case 1: total = product1 * quantity; break;
case 2: total = product2 * quantity; break;
case 3: total = product3 * quantity; break;
case 4: total = product4 * quantity; break;
case 5: total = product5 * quantity; break;
case 6: total = product6 * quantity; break;
default: System.out.println("ERROR: Invalid product number");
}
//keep reading data until the input is 0
int sum1 = 0;
while (quantity != 0) {
sum1 += quantity;
int sum2 = 0;
while (total != 0) {
sum2 +=total;
}
//read the next data
System.out.print("Enter a product number: ");
product = input.nextInt();
System.out.print("Enter quantity sold for 1 day: ");
quantity = input.nextInt();
}
//print results
System.out.println("The total number of products sold last week " + sum1);
System.out.println("The total retail value of all products sold last week " + sum2);
}
}
There are a couple scoping issues here.
First, you have placed your switch statement outside of your loop. You should place it inside your loop.
Second, there is a scoping problem with sum2. It is declared inside your sentinel loop, but referenced outside. I'm not sure why you have a nested loop adding to sum2. Here is the code with these issues resolved:
public class Mailorder {
public static void main(String[] args) {
//create a scanner
Scanner input = new Scanner(System.in);
//declare variables
double product1 = 3.75;
double product2 = 5.95;
double product3 = 8.75;
double product4 = 6.92;
double product5 = 8.75;
double product6 = 7.87;
//read in product #
System.out.print("Enter a product number: ");
int product = input.nextInt();
//read in quantity sold
System.out.print("Enter quantity sold for 1 day: ");
int quantity = input.nextInt();
//keep reading data until the input is 0
int sum1 = 0;
int sum2 = 0;
while (quantity != 0) {
sum1 += quantity;
double total = 0.00;
//switch case
switch (product)
{
case 1: total += product1 * quantity; break;
case 2: total += product2 * quantity; break;
case 3: total += product3 * quantity; break;
case 4: total += product4 * quantity; break;
case 5: total += product5 * quantity; break;
case 6: total += product6 * quantity; break;
default: System.out.println("ERROR: Invalid product number");
}
sum2 += total;
//read the next data
System.out.print("Enter a product number: ");
product = input.nextInt();
System.out.print("Enter quantity sold for 1 day: ");
quantity = input.nextInt();
}
//print results
System.out.println("The total number of products sold last week " + sum1);
System.out.println("The total retail value of all products sold last week " + sum2);
}
}
Related
My result want me to : when I enter -1 into (Enter the product number) it will directly break and calculate the total , but right now I have to enter -1 into (Enter the product number) and (Enter the quantity) only it will break
import java.util.Scanner;
public class Structuredcontrols {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
double sum=0;
double sum2=0;
double sum3=0;
int number = 0;
int quantity;
while (number != -1) {
System.out.print("Enter product number: ");
number = input.nextInt();
System.out.print("Enter quantity number: ");
quantity = input.nextInt();
switch (number) {
case 1:
sum += 2.98 * quantity;
break;
case 2:
sum2 += 4.50 * quantity;
break;
case 3:
sum3 += 9.98 * quantity;
break;
}
}
System.out.println("Total value of product 1 is: "+sum);
System.out.println("Total value of product 2 is: "+sum2);
System.out.println("Total value of product 3 is: "+sum3);
}
}
Just add a if statement
if(number == -1) {
break;
}
Here's full code
import java.util.Scanner;
public class structuredcontrols {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double sum2 = 0;
double sum3 = 0;
int number = 0;
int quantity;
while (number != -1) {
System.out.print("Enter product number: ");
number = input.nextInt();
if (number == -1)
break;
System.out.print("Enter quantity number: ");
quantity = input.nextInt();
switch (number)
{
case 1:
sum += 2.98 * quantity;
break;
case 2:
sum2 += 4.50 * quantity;
break;
case 3:
sum3 += 9.98 * quantity;
break;
}
}
System.out.println("Total value of product 1 is: " + sum);
System.out.println("Total value of product 2 is: " + sum2);
System.out.println("Total value of product 3 is: " + sum3);
}
}
I am trying to get my output to show the total cost of each item entered and a grand total of the cost of all items, the program runs but when I try to use the end-of-file indicator nothing happens, what am I missing?
package switch1;
import java.util.Scanner;
public class Switch1 {
public static void main(String[] args) {
double total = 0;
int productCounter = 0;
int aProduct = 0;
int bProduct = 0;
int cProduct = 0;
int dProduct = 0;
int eProduct = 0;
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n %s%n %s%n",
"Select your product(1=bread, 2=cheese, 3=meat, 4=msutard, 5=mayo)",
"Type the end-of-file indicator to terminate input:",
"On UNIX/Linux/macOS type <Ctrl> d then press Enter",
"On Windows type <Ctrl> z then press Enter");
while (input.hasNext()) {
int product = input.nextInt();
total += product;
++productCounter;
switch (product) {
case 1:
++aProduct;
break;
case 2:
++bProduct;
break;
case 3:
++cProduct;
break;
case 4:
++dProduct;
break;
case 5:
++eProduct;
break;
}
}
System.out.printf("%nProduct Selection:%n");
if (productCounter != 0) {
double aTotal = (aProduct * 1.89);
double bTotal = (bProduct * 3.99);
double cTotal = (cProduct * 6.99);
double dTotal = (dProduct * 1.99);
double eTotal = (eProduct * 2.99);
total = (((double)aProduct * 1.89) + ((double)bProduct * 3.99) + ((double)cProduct * 6.99) + ((double)dProduct * 1.99) + ((double)eProduct * 2.99));
System.out.printf("You ordered %d gallons of milk totaling: %f%n", aProduct, aTotal);
System.out.printf("You ordered %d loaves of bread totaling: %f%n", bProduct, bTotal);
System.out.printf("You ordered %d packages of cheese totaling: %f%n", cProduct, cTotal);
System.out.printf("You ordered %d pounds of meat totaling: %f%n", dProduct, dTotal);
System.out.printf("You ordered %d bottles of mustard totaling: %f%n", eProduct, eTotal);
System.out.printf("Your total grocery bill is: %d%n", total);
}
else {
System.out.println("No products were entered");
}
}
}
Replace scanner.hasNext with scanner.hasNextLine. If you're on a newline and you hit CTRL-D (linux) or CTRL-Z (Windows), hasNextLine should return false.
Maybe a better question is "how do I find out what am I doing wrong? "
One step would be to warp you code in a try-catch block like:
try {
//the code goes here
}catch(Exception ex) {
ex.printStackTrace();
}
And see the exceptions.
It will indicate a problem in this line
System.out.printf("Your total grocery bill is: %d%n", total);
I need to issue break a while loop if a case is matched in a switch statement. The case is as follows: if a user enters either a number less than zero or anything greater than five. I have the switch working most of my cost except the two exceptions Ive mentioned. Here is my code:
import java.util.Scanner;
public class Product
{
public static void main(String args[])
{
int cntr = 0;
int product = 0;
int units = 0;
double totalcost = 0;
Scanner MK = new Scanner(System.in);
cntr=0;
while (cntr >= 0 && cntr <=5)
{
System.out.println("Enter Product no.(1-5) or -1 to Quit");
product = MK.nextInt();
switch(product) {
case 1:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 2.98;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 2:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 4.50;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 3:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 9.98;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 4:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 4.49;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 5:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 6.87;
totalcost = totalcost + (cost*product);
System.out.println("Current total cost: " + totalcost);
cntr++;
}
case 6:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
//product = MK.nextInt();
//double cost = 2.98;
//totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
//cntr++;
}
break;
}
System.out.println("Total cost-->" +totalcost);
}
}
}
If anyone can point me in the right direction on how to stop my program when anything less than zero or greater than 5 is entered I would really appreciate it.
A couple of options:
Use a flag that you set when you want the loop to end (in your default or -1 clause), or
Use a labelled statement and a directed break in your default (or -1) clause
In this specific situation where you said you want the entire program to end, you could use System.exit
Here's more about option 2:
label: while (...) { // <== Labelled statement
switch (...) {
case ...:
// ...
break; // <=== Normal (undirected) break, just exits what
// it's in (switch in this case)
// ...
default:
break label; // <=== Directed break, exits loop
}
}
It's also handy for nested loops.
Side note: There's no need for the { and } you have surrounding the statements in your case clauses. The code for case continues until the break. (Yes, it's a bit different from other statements.)
Side note 2: You've said Enter Product no.(1-5) or -1 to Quit in your prompt, but you have cases for the values 1 to 6 (inclusive). You probably meant Enter Product no.(1-**6**) or -1 to Quit.
We were ask to make a program using the switch statement..
Here is my code:
double price = 0, totalPrice;
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
default:
System.out.println("ERROR: Invalid number!");
break;
}
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
So basically, the user will input a certain number and it will have different prices... inside the switch statements.
but if the user inputs a wrong number, it will display an error message and i dont want the user to enter the quantity which will be executed after the switch statement.
we are not allowed to use any methods or functions and i dont want to code repeatedly like this:
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
break;
case 2:
price = 410.00;
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
break;
default:
System.out.println("ERROR: Invalid number!");
break;
}
is there any other way not to use if else, methods, functions or coding repeatedly?
ANY HELP WILL BE APPRECIATED.
You can use a boolean flag and make it false if invalid option is selected.
Then only ask user further if flag is true.
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
boolean flag = true;
switch (optionNumber) {
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
default:
flag = false;
System.out.println("ERROR: Invalid number!");
break;
}
if (flag) {
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
}
Use as this:
while(!valid option)
//do this stuff
Use a flag and set it to true if the number entered is valid, so it will go to your next instruction; else ask again for input.
Throw an exception
default:
throw new InvalidArgumentException("Invalid number!");
See also InvalidArgumentException vs UnexpectedValueException
You could just remove default from the switch statement and check to see if the price is equal to 0 after the switch statement
double price = 0, totalPrice;
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
}
if (price == 0)
{
System.out.println("ERROR: Invalid number!");
}
else
{
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
}
This keeps you from adding unnecessary variables (like a boolean flag) when you already have one (price) with a default value of 0 that you can check against.
I have been working hard to find a solution, but no dice yet. I am stuck trying to find a way to total of the values of the cases in a switch statement together. I will provide the homework question and my progress. Which will include the class and classTest. Thanks for any suggestions.
THE Homework ?
A large company pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9% of their gross sales for that week. For example, a salesperson who sells $5000 worth of merchandise in a week receives $200 plus 9% of $5000, or a total of $650. You’ve been supplied with a list of the items sold by each salesperson. The values of these items are as follows:
Item Value
1 239.99
2 129.75
3 99.95
4 350.89
Develop a Java application that inputs one salesperson’s items sold for last week and calculates and displays that salesperson’s earnings. There’s no limit to the number of items that can be sold.
*********MY ISSUE:***********************
THE ISSUE ARISES WHEN I ATTEMPT TO ENTER MORE THAN ONE ITEM. THE PROGRAM WORKS WHEN I DO ONLY A SINGLE ITEM. HOWEVER, WHEN I DO MULTIPLES, THE PROGRAM NEVER TOTALS THE VALUES TOGETHER AND THE SALESPERSON EARNINGS ARE OFF
THE CLASS*********
public class SalesCommissionCalculator
{
private String item;
private double value;
public SalesCommissionCalculator()
{
setItem("");
setValue(0.0);
}
public SalesCommissionCalculator(String i, double v)
{
setItem(i);
setValue(v);
}
public void setItem(String i)
{
item = i;
}
public void setValue(double v)
{
value = v;
}
public String getItem()
{
return item;
}
public double getValue()
{
return value;
}
public String toString()
{
return ("Item"+item+"Value"+value);
}
}
************THE ClassTest:
import javax.swing.JOptionPane;
import java.util.Scanner;
public class SalesCommissionCalculatorTest
{
public static void main(String args [])
{
int quantity;
int item;
double salary = 200.00;
double commission = 0.09;
double total= 0;
String msg="";
SalesCommissionCalculator item1 = new SalesCommissionCalculator("1", 239.99);
SalesCommissionCalculator item2 = new SalesCommissionCalculator("2", 129.75);
SalesCommissionCalculator item3 = new SalesCommissionCalculator("3", 99.95);
SalesCommissionCalculator item4 = new SalesCommissionCalculator("4", 350.89);
item=Integer.parseInt(JOptionPane.showInputDialog("Enter item number 1, 2, 3 or 4. Enter -1 to quit."));
while(item != -1)
{
switch(item)
{
case 1: quantity=Integer.parseInt(JOptionPane.showInputDialog("Enter quantity"));
total = (quantity*item1.getValue());
break;
case 2: quantity=Integer.parseInt(JOptionPane.showInputDialog("Enter quantity"));
total= (quantity*item2.getValue());
break;
case 3: quantity=Integer.parseInt(JOptionPane.showInputDialog("Enter quantity"));
total = (quantity*item3.getValue());
break;
case 4: quantity=Integer.parseInt(JOptionPane.showInputDialog("Enter quantity"));
total = (quantity*item4.getValue());
break;
default:
System.out.println("Invalid Item Number");
}
item=Integer.parseInt(JOptionPane.showInputDialog("Enter item number 1, 2, 3 or 4. Enter -1 to quit."));
}
msg = msg + String.format("Your Commission is $%.2f", (total*commission)+salary);
JOptionPane.showMessageDialog(null, msg);
}
}
You aren't accumulating the total in any of the cases. What you have right now (using case 1 as an example)
total = (quantity*item1.getValue());
just sets the total to be equal to quantity*item1.getValue(). What you probably wanted was
total += (quantity*item1.getValue());
instead. (and similarly for the other three cases)
import java.util.*;
public class Sale {
public static void main(String[] args) {
double value;
int item;
double earn= 0.0;
double total=0.0;
Scanner console = new Scanner(System.in);
System.out.print("Enter 1, 2, 3, 4 or \"-1 to quit\": ");
item = console.nextInt();
while(item != -1)
{
switch(item)
{
case 1:
System.out.print("Enter quantity: ");
int quantity= console.nextInt();
total = quantity * 239.99;
break;
case 2:
System.out.print("Enter quantity:");
quantity= console.nextInt();
total = quantity * 129.75;
break;
case 3:
System.out.print("Enter quantity: ");
quantity= console.nextInt();
total= quantity * 99.95;
break;
case 4:
System.out.print("Enter quantity: ");
quantity= console.nextInt();
total= quantity * 350.89;
break;
default: System.out.print("Invalid Item!");
}
if (total>=5000)
{
earn= total * 0.09;
System.out.print("You have earned 9%, Your salary of the week : $"+earn);
}
else
System.out.println("Your salary of the week: $"+total);
System.out.println("");
System.out.print("Enter 1, 2, 3, 4 or \"-1 to quit\": ");
item = console.nextInt();
}
System.out.println("Thank you to visit our shop!");
}
}