The function of (+=) in switch case is not working - java

I thought using += the total will sum the result , but he reset everything after I insert again.
import java.util.Scanner;
public class Week3_Lab {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int product;
int amount;
while(true){
System.out.print("Enter the product number(1-3): ");
product = input.nextInt();
if (product == -1){
break;
}
System.out.print("Enter the total amount of product: ");
amount = input.nextInt();
num(product, amount);
}
}
public static int num(int product , int amount){
double total_1 = 0;
double total_2 = 0;
double total_3 = 0;
switch (product){
case 1 :
total_1 += amount * 2.98;
break;
case 2 :
total_2 += amount * 4.50;
break;
case 3 :
total_3 += amount * 9.98;
break;
}
System.out.println("The total of product 1 is : "+ total_1);
System.out.println("The total of product 2 is : "+ total_2);
System.out.println("The total of product 3 is : "+ total_3);
return product;
}
}

Your variables total_1, total_2 and total_3 are local and not shared between method calls and therefore for each call be initialized to 0.
If you don't want this to happen define them outside of the method body.
static double total_1=0;
static double total_2=0;
static double total_3=0;
public static int num(int product , int amount){
switch (product){
//...
}
//...
}

You have initialized your total_1 to 0, so the program is output is simply (amount * 2.98) as shown below:
total_1 = 0 + (amount * 2.98);
The same concept is applied for total_2 and total_3 as well.

Related

I have to do this task (online shop) using "switch" statements. I got stuck

"Write a Java program to simulate an online store. The program should begin
by displaying a list of products and their prices. There should be a minimum of 4
products offered.
My code is below, it works without the strings but I need to have names for the cakes(display names and prices)
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input= new Scanner(System.in)
int cakeNo = 0;
double cake1;
double cake2;
double cake3;
double cake4;
double cake5;
int quantity;
double totalSales = 0;
while(cakeNo !=0 )
System.out.println("Enter cake number 1-5");
cakeNo=input.nextInt();
System.out.println("Enter quantity");
quantity = input.nextInt();
switch (cakeNo){
case 1: cake1 = 3.70;
totalSales+=(3.70*quantity);
break;
case 2: cake2 = 4.20;
totalSales+=(4.20*quantity);
break;
case 3: cake3 = 4.50;
totalSales+=(4.50*quantity);
break;
case 4: cake4 = 5.00;
totalSales+=(5.00*quantity);
break;
case 5: cake5 = 5.50;
totalSales+=(5.50*quantity);
break;
}
System.out.println(totalSales);
}
}
Thank you so much for reading! Please help if you have an idea.
Well there are a few things wrong in your code that you should take care first.
First: The first 5 string are wrongly defined. It should be like this String cake1 = "Angel cake" and so on.
Second: The strings and doubles have the same names you cannot do that. You need to have something like String cake1Name = "Name" and double cake1Price = price this way you have two distinct properties for everycake.
Third: Right now the code doesn't even enters the while loop. Since cakeNo starts with 0 and the condition in your while loop is cakeNo != 0 right on before the first loop this condition will be tested and it will be false meaning that the loop code won't be executed and will jump to the end of the program.
After this fixes there is still a little problem. After you get the input from the user if said input is 0 meaning that he wants to leave the program will still ask him for a quantity. You need to add/change something that breaks the loop when this conditions is true. I don't want to give you code but I hope this answer can help you good luck :)
This is what I would do:
public class Main {
LinkedList<Product> cart = new LinkedList<Product> ();
Scanner scanner = new Scanner(System.in);
double tax = 7.5;
boolean done = false;
public Main() {
cart.add(new Product("Cake 1", 3.70));
cart.add(new Product("Cake 2", 4.20));
cart.add(new Product("Cake 3", 4.50));
cart.add(new Product("Cake 4", 5.00));
cart.add(new Product("Cake 5", 5.50));
}
public void displayCart() {
for (int i = 0; i < cart.size(); i++) {
switch (cart.get(i).quantitySelected){
case 0:
System.out.println(i + ": " + cart.get(i).name + " none selected");
break;
default:
System.out.println(i + ": " + cart.get(i).name + " selected: " + cart.get(i).quantitySelected);
break;
}
}
}
public void addToCart(int product, int amount) {
cart.get(product).select(amount);
}
public void getSelection() {
int productSelected;
System.out.println("enter a product value or FINNISHED to end: ");
try {
productSelected = scanner.nextInt();
} catch (InputMismatchException e) {
done = true;
return;
}
System.out.println("enter amount to select: ");
int amount = scanner.nextInt();
cart.get(productSelected).select(amount);
}
public double getSubtotal() {
double cost = 0.00;
for (Product product : cart) {
cost += product.cost * product.quantitySelected;
}
return cost;
}
public double getTotal() {
return getSubtotal() + getSubtotal()*tax;
}
public void finnishPurchase() {
System.out.println("---------------------");
System.out.println("subtotal: " + getSubtotal());
System.out.println("tax: " + tax);
System.out.println("total: " + getTotal());
}
public static void main(String[] args) {
Main store = new Main();
while (!store.done) {
store.displayCart();
store.getSelection();
}
store.finnishPurchase();
}
}
public class Product {
String name;
double cost;
int quantitySelected = 0;
public Product(String name, double cost) {
this.name = name;
this.cost = cost;
}
public void select(int quantity) {
quantitySelected = quantity;
}
}

Cannot break small payroll system in different methods

I want to start by saying that I'm a newby in Java, and it's also my first time asking something on this site. After 3 days trying to figure out how to break this small program in methods, I haven't been able to do so. could anyone help me with it ?
I've been reading and it looks like I'm violating the single responsibility principle. Any opinions would be more than welcome.
public class RateSystem {
double employeeSalary;
public int salaryRate(String employeePosition) {
if (employeePosition.equalsIgnoreCase("1")) {
return 40;
} else if (employeePosition.equalsIgnoreCase("2")) {
return 30;
} else
employeePosition.equalsIgnoreCase("3");
return 50;
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Employee position please...");
System.out.println("Press 1 for IT " + "\n" + "Press 2 for Tech" +
"\n" + "Press 3 for engineer");
String ePosition = input.nextLine();
RateSystem raul = new RateSystem();
int getPay = raul.salaryRate(ePosition);
System.out.println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
int totalPay = 0;
if (weekHours <= 40) {
totalPay = getPay * weekHours;
System.out.println("Employee salary is " + totalPay);
} else {
int overTimeHours = weekHours - 40;
int extra$$PerOverTime = overTimeHours * getPay +(overTimeHours * getPay/2);
totalPay = getPay * (weekHours - overTimeHours);
System.out.println("The employee accumulated 40 hours equivalent to $"+
totalPay + " plus $" + extra$$PerOverTime + " overtime hours, a total of $"+(extra$$PerOverTime + totalPay));
}
}
}
If we are looking at main(), It does multiple tasks:
Receive user input
Calculate total pay and possible other finance information
Print the results
How's that for starters
I see followings could be added.
1) Salaries are created for Employees so why don't you create and Employee class and encapsulate details inside it like "employeePosition". So you can add more things later and having setters inside it you will get the chance of changing setter logics for employees.
2) You can create a Calculator class and create methods accepting single Employee or a List of Employees and calculate their Salary Rates.
3) You also can add a Printing related class. So you can produce different printing for single or List of Employees or may be like a tabular format.
I have identified following methods in your code.
1) showMainMenu --> responsible to show menu to the user
2) readMenuSelection --> here you will read whatever user has selected in the main menu. It should be read in int value rather than string.
3) For each Selection from menu there will be separate methods such as payForIT(), payForTech() and payForEngineer()
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Employee position please...");
System.out.println("Press 1 for IT " + "\n" + "Press 2 for Tech" + "\n" + "Press 3 for engineer");
String position = input.nextLine();
RateSystem rateSystem = new RateSystem();
rateSystem.setEmployeePosition(position);
System.out.println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
rateSystem.setWeekHours(weekHours);
rateSystem.calculateSalary();
int totalPay = rateSystem.getTotalPay();
int overTime = rateSystem.getOvertime();
if (overTime > 0) {
System.out.println("The employee accumulated 40 hours equivalent to $" + totalPay + " plus $" + overTime
+ " overtime hours, a total of $" + (overTime + totalPay));
} else {
System.out.println("Employee salary is " + totalPay);
}
}
}
public class RateSystem {
private final int STANDARD_WORK = 40;
private double employeeSalary;
private int weekHours;
private Position employeePosition;
private int totalPay = 0;
private int overTime = 0;
public void setEmployeePosition(String position) {
employeePosition = Position.fromString(position);
}
public void setWeekHours(int weekHours) {
this.weekHours = weekHours;
}
public int getTotalPay() {
return totalPay;
}
public int getOvertime() {
return overTime;
}
public void calculateSalary() {
int salaryRate = employeePosition.getRate();
int workhours = (weekHours > STANDARD_WORK) ? STANDARD_WORK : weekHours;
int overTimeHours = (weekHours > STANDARD_WORK) ? (weekHours - STANDARD_WORK) : 0;
totalPay = workhours * weekHours;
overTime = (overTimeHours * salaryRate) + (overTimeHours * salaryRate / 2);
}
}
public enum Position {
IT(40), Tech(30), Engineer(50);
private int rate = 0;
Position(int r) {
rate = r;
}
public int getRate() {
return rate;
}
public static Position fromString(String position) {
switch (position) {
case "1":
return IT;
case "2":
return Tech;
case "3":
return Engineer;
}
return null;
}
}
To follow single responsibility principle you have to create method for each common task in your program. That helps do not repeat code and helps to modify code in one place.
I have created separate methods for building string and for printing string as you use it frequently in your code:
package com.stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
println("Employee position please...");
println(buildString("Press 1 for IT ", "\n", "Press 2 for Tech", "\n", "Press 3 for engineer"));
String ePosition = input.nextLine();
RateSystem raul = new RateSystem();
int getPay = raul.salaryRate(ePosition);
println("How many hours did he work for the week?...");
int weekHours = input.nextInt();
int totalPay = 0;
if (weekHours <= 40) {
totalPay = getPay * weekHours;
println(buildString("Employee salary is ", String.valueOf(totalPay)));
} else {
int overTimeHours = weekHours - 40;
int extra$$PerOverTime = overTimeHours * getPay + (overTimeHours * getPay / 2);
totalPay = getPay * (weekHours - overTimeHours);
println(buildString("The employee accumulated 40 hours equivalent to $", String.valueOf(totalPay),
" plus $", String.valueOf(extra$$PerOverTime), " overtime hours, a total of $",
String.valueOf((extra$$PerOverTime + totalPay))));
}
}
private static String buildString(String... strings) {
StringBuilder builder = new StringBuilder();
for (String string : strings) {
builder.append(string);
}
return builder.toString();
}
private static void println(String s) {
System.out.println(s);
}
}
And class RateSystem:
package com.stackoverflow.main;
public class RateSystem {
double employeeSalary;
public int salaryRate(String employeePosition) {
if (equalsIgnoreCase(employeePosition, "1")) {
return 40;
} else if (equalsIgnoreCase(employeePosition, "2")) {
return 30;
} else if (equalsIgnoreCase(employeePosition, "3"))
return 50;
return 0;
}
private boolean equalsIgnoreCase(String arg1, String arg2) {
return arg1.equalsIgnoreCase(arg2);
}
}

While loop not working accordingly

The following code asks the user to input the description, price and quantity of item he consumed.
There is a while loop to ask if he wants to input more items! If he does, the program ask to insert another description, price and quantity of the other items, and so on.
If he doesn't want to input more items, the output is all the items he added to the array, and the total of the bill.
Problem is: the first time the while runs, it works, but on the second time if the user answer with "y", it returns an error, as if he jumped from the description right to the price of the second item. If the user type the description, then it gets an input mismatch exception.
Main Class:
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Gastos> billArr = new ArrayList<>();
Scanner input = new Scanner(System.in);
int qntItems = 0 , counter = 0;
String ans;
Gastos bill = new Gastos();
while (qntItems == 0) {
System.out.print("Want to input another item? Y/N: ");
ans = input.nextLine();
switch (ans){
case "y":
qntItems = 0;
bill.setDescription();
bill.setPrice();
bill.setQuantity();
bill.getTotal();
billArr.add(bill);
counter = counter + 1;
break;
case "n": qntItems = 1;
break;
default: System.out.print("Invalid!");
System.out.println();
break;
}
input.close();
}
for (int i = 0; i < billArr.size();i++){
System.out.print(bill.getDescription() + ", " + bill.getPrice() + ", " + bill.getQuantity() + ", " + "the total is: " + bill.getTotal());
}
}
}
and the Gastos class:
package com.company;
import java.util.Scanner;
public class Gastos {
private String description;
private double price, quantity, total;
private Scanner input = new Scanner(System.in);
public void setDescription(){
System.out.print("Insert the item name: ");
description = input.nextLine();
}
public void setPrice(){
System.out.print("insert the item price: ");
price = input.nextDouble();
}
public void setQuantity(){
System.out.print("Insert the quantity: ");
quantity = input.nextDouble();
}
public String getDescription(){
return description;
}
public double getPrice() {
return price;
}
public double getQuantity() {
return quantity;
}
public double getTotal(){
total = price * quantity;
return total;
}
}
How can I handle this error?
You have a bug in your 2nd loop.
It should be:
System.out.print(billArr.get(i).getDescription().....
or simply put:
for(Gastos b : billArr){
System.out.print(b.getDescription())
}
Update 1: Another error is you close the Scanner at the end of the first loop. Move input.close(); outside the loop or inside case "n".
Update 2: You have another problem, you need to reinitialize Gastos every time you enter new details about it. So you need to do Gastos bill = new Gastos(); right after case "y": and remove it from where you initialize it before the while loop. Your main should look like this:
public static void main(String[] args) {
ArrayList<Gastos> billArr = new ArrayList<>();
Scanner input = new Scanner(System.in);
int qntItems = 0 , counter = 0;
String ans;
while (qntItems == 0) {
System.out.print("Want to input another item? Y/N: ");
ans = input.nextLine();
switch (ans){
case "y":
Gastos bill = new Gastos();
qntItems = 0;
bill.setDescription();
bill.setPrice();
bill.setQuantity();
bill.getTotal();
billArr.add(bill);
counter = counter + 1;
break;
case "n": qntItems = 1;
input.close();
break;
default: System.out.print("Invalid!");
System.out.println();
break;
}
}
for (Gastos bill : billArr){
System.out.print(bill.getDescription() + ", " + bill.getPrice() + ", " + bill.getQuantity() + ", " + "the total is: " + bill.getTotal());
}
}
I think you need to spend sometime debugging and understanding how java's objects work. These are basic errors which should be easily caught.

Calculate average value in array

I am working on a project in Java that requests user inputs information like name, id, score in array.I need to help about calculate a average grade that user input and how to find out who have highest score. Here is my code:
package finalproject;
import java.util.Scanner;
public class FinalProject {
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Cis84[] student = new Cis84[50];
int option;
for (int c = 0; c < 50; c++)
student[c] = new Cis84();
do {
System.out.print("");
System.out.println("1) Add Information");
System.out.println("2) Show report");
System.out.println("3) Exit");
System.out.print("\nEnter option: ");
option = input.nextInt();
switch (option) {
case 1:
String n;
double g;
int index,
i;
System.out.println("Which position of the student?");
index = input.nextInt();
System.out.println("What is the student's name:");
n = input.nextLine();
n = input.nextLine();
System.out.println("What is student's Id");
i = input.nextInt();
System.out.println("What is student's score");
g = input.nextDouble();
student[index].setName(n);
student[index].setGrade(g);
student[index].setId(i);
break;
case 2:
for (int c = 0; c < 50; c++)
System.out.println(student[c]);
break;
case 3:
System.out.println("You are done");
break;
default:
System.out.println("Try again");
break;
}
} while (option != 3);
}
}
and class
package finalproject;
public class Cis84 {
private String name;
private int id;
private double grade;
public Cis84() {
name = "not input yet";
id = 00000;
grade = 0.0;
}
public Cis84(String n, int i, double g) {
name = n;
id = i;
grade = g;
}
public void setName(String n) {
name = n;
}
public void setId(int i) {
id = i;
}
public void setGrade(double g) {
grade = g;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public double getGrade() {
return grade;
}
public String toString() {
return String.format("%s\n%d\n%.2f\n", name, id, grade);
}
}
This is for homework, clearly, and I don't feel comfortable giving you a straight answer. However, what you will want to do is when it is time to display the averages, go through the entire students array and sum up the scores, then divide by the size of the array, likely using a for loop. You could keep track of the size of the array by having a counter increased anytime option 1 of the switch-case is called.
To find the highest score, you should be able to use the average-calculation for loop mentioned above, and check the grade against the previous highest grade. Record the index of whichever has the highest grade and print it out.
Have some pseudocode!
for(size of array which isn't NULL){
add indexed grade to sum;
check to see if this index has the highest grade;
}
display (sum/size); //the average
display highest grade;
calculating average would be something like the below code. Remember, average is the sum of all the values divided by the total number of values
double sum = 0, divisor = 0;
for (int k = 0; k < student.length; k++){
sum += student[k].getGrade();//add up all the grades
divisor = k;//get the number of total items
}
return sum/divisor; //divide
private static double calculateAverage(Cis84[] students) {
double sum = 0;
for (Cis84 student : students) {
sum += student.getGrade();
}
return sum / students.length;
}
private static double calculateHighestScore(Cis84[] students) {
double highestScore = 0;
for (Cis84 student : students) {
if (student.getGrade() > highestScore) {
highestScore = student.getGrade();
}
}
return highestScore;
}
Then, to show the information:
case 2:
System.out.println("Average:");
System.out.println(calculateAverage(student));
System.out.println("Highest score:");
System.out.println(calculateHighestScore(student));

return issue for method

I am having an issue with a method returning to the main method. It is saying that amount in "return amount" cannot be resolved to a variable. Where am I off on this??
This is the message I get:
Multiple markers at this line
- Void methods cannot return a
value
- amount cannot be resolved to a
variable
Here is the code:
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
amount = temp;
System.out.print((count + 1) + " " + temp);
}
{
return amount;
}
}
You curly braces are not correct. The compiler - and me - was confused about that.
This should work (at least syntactically):
import java.util.Scanner;
public class Investment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years));
}
public static double futureInvestmentValue(
double amount, double interest, int years) {
double monthlyInterest = interest / 1200;
double temp = 0;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest, years * 12));
amount = temp;
System.out.print((count + 1) + " " + temp);
return amount;
}
}
Remove amount from its own scope As a start. Also from the method futureInvestmentValue, you take in amount as an argument but the value is never modified so you're returning the same value being passed which is most likely not the desired outcome.
remove return amount from its own scope
the method futureInvestmentValue... You can't modify any of the parameters inside the method so you have to declare another variable besides amount inside the method (maybe it's the temp variable you keep using) and return that instead
when you return something, the return statement is always inside the method. Never outside it while inside its own braces (never seen this before...)
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years) {
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
System.out.print((count + 1) + " " + temp);
}
return amount;
}
}

Categories

Resources