I keep getting this error and I am not stuck trying to fix it.
package bonuscalc;
import java.text.DecimalFormat;
import java.util.Scanner;
public class BonusCalc {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat formatter = new DecimalFormat("#0.00");
int Salary;
double NewSal, Comm;
double p1 = 0.1;
double p2 = 0.15;
double p3 = 0.2;
double p4 = 0.3;
System.out.println("Welcome to Bonus Calculator");
do{
System.out.print("Enter your Salary: ");
Salary = input.nextInt();
}While (Salary < 0)
if((Salary > 0) && (Salary <= 8000)){
Comm = (Salary * p1);
NewSal = Salary + Comm;
System.out.print("Your Commition is RM" + formatter.format(Comm));
System.out.println(" and your New Salary is RM" + formatter.format(NewSal));
}
else if((Salary > 8000) && (Salary <= 15000)){
Comm = (Salary * p2);
NewSal = Salary + Comm;
System.out.print("Your Commition is RM" + formatter.format(Comm));
System.out.println(" and your New Salary is RM" + formatter.format(NewSal));
}
else if((Salary > 15000) && (Salary <= 25000)){
Comm = (Salary * p3);
NewSal = Salary + Comm;
System.out.print("Your Commition is RM" + formatter.format(Comm));
System.out.println(" and your New Salary is RM" + formatter.format(NewSal));
}
else if(Salary > 25000){
Comm = (Salary * p4);
NewSal = Salary + Comm;
System.out.print("Your Commition is RM" + formatter.format(Comm));
System.out.println(" and your New Salary is RM" + formatter.format(NewSal));
}
else{
System.out.println("Input invalid. Renter Salary");
}
}
}
You have written While instead of while.
do {
...
} While (Salary < 0);
correct would be:
do {
...
} while (Salary < 0);
Hope this solves your problem.
Your do-while loop has an invalid syntax. Firstly, while is lowercase, thus While is incorrect. Moreover, you are missing a semicolon.
do {
System.out.print("Enter your Salary: ");
Salary = input.nextInt();
} while (Salary < 0);
On a side note, in Java variables usually start with lowercase letters. It is not a strict rule, but a convention that it is prudent to conform to.
Related
I am trying to make a salary calculator that if the applicant is under 18, they cannot receive overtime, because in the state I am in the maximum allowed for minors is 18 hours. I have it set where you cannot earn overtime until you reach 40 hours. Is there anything I can do for this?
import java.util.Scanner;
public class SalaryV2
{
public static void main(String[] args)
{
//Declare and initialize variables
double totalSalary;
boolean isOvertime;
Scanner in = new Scanner(System.in);
//Input
System.out.print("Please enter your name (first last): ");
String firstName = in.next();
String lastName = in.nextLine();
System.out.print("Please enter your age: ");
String customerAge = in.nextLine();
double age = Double.parseDouble(customerAge);
System.out.print("\nWhat is your hourly rate of pay: ");
String rateOfPay = in.nextLine();
double payRate = Double.parseDouble(rateOfPay);
System.out.print("\nHow many hours did you work: ");
String totalHoursWorked = in.nextLine();
double totalHours = Double.parseDouble(totalHoursWorked);
System.out.println();
//Processing
if(17 > age)
{
isOvertime = false;
totalSalary = totalHours * payRate;
}
else if(totalHours > 40)
{
if(totalHours > 40)
{
isOvertime = true;
totalSalary = 40 * payRate + (totalHours - 40) * payRate * 1.5;
}
else
{
isOvertime = false;
totalSalary = totalHours * payRate;
}
}
//Output
System.out.print("Employee Name: " + lastName + ", " + firstName\n);
System.out.print("Hours worked: " + totalHours);
System.out.println("\t\tOvertime: " + isOvertime +);
System.out.println("Salary: " + totalSalary);
}
}
Keep it simple, no need for else-if-if,
import java.util.Scanner;
public class SalaryV2{
public static void main(String[] args){
//Declare and initialize variables
double totalSalary= 0;
boolean isOvertime = false;
Scanner in = new Scanner(System.in);
//Input
System.out.print("Please enter your name (first last): ");
String firstName = in.next();
String lastName = in.nextLine();
System.out.print("Please enter your age: ");
String customerAge = in.nextLine();
double age = Double.parseDouble(customerAge);
System.out.print("\nWhat is your hourly rate of pay: ");
String rateOfPay = in.nextLine();
double payRate = Double.parseDouble(rateOfPay);
System.out.print("\nHow many hours did you work: ");
String totalHoursWorked = in.nextLine();
double totalHours = Double.parseDouble(totalHoursWorked);
System.out.println();
//Processing
if(age >= 18 && totalHours > 40) {
isOvertime = true;
totalSalary = 40 * payRate + (totalHours - 40) * payRate * 1.5;
}else{
isOvertime = false;
totalSalary = totalHours * payRate;
}
//Output
System.out.print("Employee Name: " + lastName + ", " + firstName +'\n' );
System.out.print("Hours worked: " + totalHours + '\n');
System.out.println("Overtime: " + isOvertime );
System.out.println("Salary: " + totalSalary);
}}
With the following input STDIN
firstname lastname
19
10
42
Output :
$javac SalaryV2.java
$java -Xmx128M -Xms16M SalaryV2
Please enter your name (first last): Please enter your age:
What is your hourly rate of pay:
How many hours did you work:
Employee Name: lastname, firstname
Hours worked: 42.0
Overtime: true
Salary: 430.0
If under 18 STDIN
firstname lastname
17
10
42
Output :
$javac SalaryV2.java
$java -Xmx128M -Xms16M SalaryV2
Please enter your name (first last): Please enter your age:
What is your hourly rate of pay:
How many hours did you work:
Employee Name: lastname, firstname
Hours worked: 42.0
Overtime: false
Salary: 420.0
Checked by executing the above code.
If you are a minor you cannot get additional pay for any overtime you work (strange as that may seem).
If you have less than 40 hours you cannot get pay for overtime (everybody knows the weird consequences of that...).
So you can only get paid for overtime if you are over 18 and have more than 40 hours.
if((18 <= age) && (totalHours > 40))
{
isOvertime = true;
totalSalary = 40 * payRate + (totalHours - 40) * payRate * 1.5;
} else
{
isOvertime = false;
totalSalary = totalHours * payRate;
}
I.e. I do not see the need for nested ifs.
I didn't understand very well your question, but here is something you can improve.
In the first if, you are not considering even 17 years old, you should put if(17 >= age) or if(18 > age).
Then, in the else if you put the same condition as the if below, so what you should do is:
else if(totalHours > 40)
{
isOvertime = true;
totalSalary = 40 * payRate + (totalHours - 40) * payRate * 1.5;
}
else
{
isOvertime = false;
totalSalary = totalHours * payRate;
}
And to make your code more efficient, you can put two conditions in one if.
if(18 > age && totalHours > 40)
{
isOvertime = false;
totalSalary = totalHours * payRate;
}
else
{
isOvertime = true;
totalSalary = 40 * payRate + (totalHours - 40) * payRate * 1.5;
}
I didn't check if the code actually works, but it should be fine
I am having trouble with a part of an assignment where i have a method to calculate the regular pay of an employee but if the hours worked is over 40 then the rest is overtime but in if the user types in 50 hours with a 10 dollar rate it will print out 500 but i want it to to only print out 40 of those 50 hours and take the rest as overtime.
package paytime;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String firstName, lastName, choice;
double hoursWorked, hourlyWage, weeklyPay;
Employee one = new Employee();
System.out.print("Enter Y to process employee or any other key to end: ");
choice = scn.nextLine();
if (choice.equalsIgnoreCase("Y"))
{
System.out.print("Enter employee number: ");
int number = scn.nextInt();
while (!one.findEmpNumber(number))
{
System.out.print("Invlaid, enter a proper employee number: ");
number = scn.nextInt();
}
System.out.print("Enter first name: ");
firstName = scn.next();
System.out.print("Enter last name: ");
lastName = scn.next();
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextDouble();
while (hoursWorked < 0)
{
System.out.print("Negative hours not allowed. Enter hours worked: ");
hoursWorked = scn.nextDouble();
}
System.out.print("Enter hourly wage: $");
hourlyWage = scn.nextDouble();
while (hourlyWage < 0 || hourlyWage > 100)
{
System.out.print("Negative wage is not allowed or wage entered is to high. Enter hourley wage: $");
hourlyWage = scn.nextDouble();
}
System.out.println(" ");
if (hoursWorked <= 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked = 40, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
}
else if (hoursWorked > 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
System.out.println(" ");
System.out.println(" ");
System.out.println("Worker " + number + " Overtime Calculation");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callOvertimePay());
}
}
else
{
System.out.println("Total number of Employees processed: ");
}
}
}
package paytime;
public class Employee {
private int empNumbers [] = {101, 103, 106, 109, 110, 113, 116, 118, 120};
public double weeklyPay, hoursWorked, hourlyWage, incomeTax, netPay, actualOvertimeHours, overtimePay, overtimeHours;
public double overtimeWage = hourlyWage * 1.5;
public boolean findEmpNumber(int number)
{
boolean found = false;
for (int sub = 0; sub < empNumbers.length; sub++)
{
if (number == empNumbers[sub])
{
found = true;
break;
}
}
return found;
}
private void calculateWeeklyPay(double hoursWorked, double hourlyWage) {
weeklyPay = hoursWorked * hourlyWage;
}
public double callWeeklyPay(double hoursWorked, double hourlyWage) {
calculateWeeklyPay(hoursWorked, hourlyWage);
return weeklyPay;
}
private void calculateIncomeTax() {
if (weeklyPay > 0.0 && weeklyPay <= 300.0)
{
incomeTax = weeklyPay * 0.10;
}
else if (weeklyPay > 300.1 && weeklyPay <= 400.0)
{
incomeTax = weeklyPay * 0.12;
}
else if (weeklyPay > 400.1 && weeklyPay <= 500.0)
{
incomeTax = weeklyPay * 0.15;
}
else if (weeklyPay > 500.1)
{
incomeTax = weeklyPay * 0.20;
}
}
public double callIncomeTax() {
calculateIncomeTax();
return incomeTax;
}
private void calculateNetPay() {
netPay = weeklyPay - incomeTax;
}
public double callNetPay() {
calculateNetPay();
return netPay;
}
private void calculateOvertimePay() {
overtimeHours = hoursWorked -40;
overtimePay = ovetimeHours * overtimeWage;
}
public double callOvertimePay() {
calculateOvertimePay();
return overtimePay;
}
}
When you call callWeeklyPay method subtract 40 from the hoursWorked.
one.callWeeklyPay(hoursWorked - 40, hourlyWage));
But I would suggest moving the logic of checking for overtimes(hours exceeding 40) inside the Employee class (callWeeklyPay method) itself.
I'm having a problem with this Java code. It's a questionnaire that should calculate your grade. It all goes and runs well until the very last part where it says "current score" that whole equation should equal 33.16 but instead it equals 24.
I changed some values, did some research but I haven't found what I'm looking for.
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
System.out.println("Grading Scale:");
System.out.println("A\t 90 - 100");
System.out.println("B\t 80 - 89");
System.out.println("C\t 70 - 79");
System.out.println("D\t 60 - 69");
System.out.println("F\t below 60");
System.out.println("What letter grade do you want to achieve for the course?");
String desiredGrade;
Scanner keyboard = new Scanner(System.in);
desiredGrade = keyboard.next();
if (desiredGrade.equalsIgnoreCase("A") || desiredGrade.equalsIgnoreCase("B")
|| desiredGrade.equalsIgnoreCase("C") || desiredGrade.equalsIgnoreCase("D")
|| desiredGrade.equalsIgnoreCase("F")) {// is this necessary? vv
System.out.println("Enter Percentage Weights");
}
else {
System.out.println("Input error.");
System.exit(0);
}
int exam1, exam2, finalExam, labs, projects, attendance, quizzes;
System.out.println("Exam 1:\t");
exam1 = keyboard.nextInt();
System.out.println("Exam 2:\t");
exam2 = keyboard.nextInt();
System.out.println("Final Exam:\t");
finalExam = keyboard.nextInt();
System.out.println("Labs:\t");
labs = keyboard.nextInt();
System.out.println("Projects:\t");
projects = keyboard.nextInt();
System.out.println("Attendance:\t");
attendance = keyboard.nextInt();
System.out.println("Quizzes:\t");
quizzes = keyboard.nextInt();
// so the semicolon isn't needed after the if statement?
if (exam1 + exam2 + finalExam + labs + projects + attendance + quizzes != 100) {
System.out.println("Weights don't add up to 100, program exiting");
System.exit(0);
}
System.out.println("Enter your scores out of a 100:");
System.out.println("Do you know your Exam 1 score?");
String answer;
int exam1score = 0, exam2score = 0, finalExamScore = 0, labAverage = 0, projectAverage = 0, quizAverage = 0, attendanceAverage = 0;
double currentScore = 0;
answer = keyboard.next();
// ask about this
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
// why can't i put int here?
System.out.println("Score received on exam 1:");
exam1score = keyboard.nextInt();
System.out.println("Do you know your Exam 2 score?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Score received on exam 2:");
exam2score = keyboard.nextInt();
System.out.println("Do you know your Final Exam score?");
answer = keyboard.next();
}
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Score received on final exam");
finalExamScore = keyboard.nextInt();
}
}
System.out.println("Do you know your lab average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Lab Grade:");
labAverage = keyboard.nextInt();
}
System.out.println("Do you know your project average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Project Grade:");
projectAverage = keyboard.nextInt();
}
System.out.println("Do you know your quiz average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Quiz Grade:");
quizAverage = keyboard.nextInt();
}
System.out.println("Do you know your attendance average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Attendance Grade:");
attendanceAverage = keyboard.nextInt();
}
currentScore = ((double)exam1score*exam1 + exam2score*exam2 +finalExam*finalExamScore + labs*labAverage + projects*projectAverage + attendance*attendanceAverage + quizzes*quizAverage)/((double)exam1+exam2+finalExam+labs+projects+attendance+quizzes);
System.out.println("Current Grade Score:\t " + currentScore);
String grade;
if (currentScore >= 90)
grade = "A";
else if (currentScore >= 80)
grade = "B";
else if (currentScore >= 70)
grade = "C";
else if (currentScore >= 60)
grade = "D";
else
grade = "F";
}
}
The following only converts the exam1score*exam1 value to double, not the entire expression.
(double) exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore + ....
So, you should do something like this.
int nominator = exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore
+ labs*labAverage + projects*projectAverage
+ attendance*attendanceAverage + quizzes*quizAverage;
int denominator = exam1 + exam2 + finalExam + labs + projects + attendance + quizzes;
currentScore = (double) nominator / denominator;
OR
int nominator = exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore
+ labs*labAverage + projects*projectAverage
+ attendance*attendanceAverage + quizzes*quizAverage);
int denominator = exam1 + exam2 + finalExam + labs + projects + attendance + quizzes;
currentScore = (nominator * 1.0) / denominator;
(double)exam1score*exam1 + exam2score*exam2 +finalExam*finalExamScore + labs*labAverage + projects*projectAverage + attendance*attendanceAverage + quizzes*quizAverage
only converts the first one to double and leaves the rest as int.
I have a project in my programming class that has to give a PayRoll scenario which contains three classes including PayRoll, PayRollTester, and EmployeeRecord. My code compiles and prints the EmployeeRecord correctly but does not list the PayRoll correctly. Instead, I receive an error saying Error: Out of Bounds of ArrayList.
Payroll:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Date;
// ...javadoc...
public class Payroll
{
//ArrayLists that will use methods from EmployeeRecords.
ArrayList<String> employeeNames2;
ArrayList<Double> employeeWages2;
ArrayList<Integer> emID = new ArrayList<Integer>();
ArrayList<Double> hours = new ArrayList<Double>();
ArrayList<Double> totalPay = new ArrayList<Double>();
//Creating the hours and wages variables.
private double hoursWorked = 0.0;
private double hoursWorked2 = 0.0;
private int weeks = 0;
private String employeeID = "%03d";
private int quit = 1000;
private int i = 1;
Scanner input = new Scanner(System.in);
public void setEmployeePayroll()
{
// Constructs a new EmployeeRecord.
EmployeeRecord e = new EmployeeRecord();
e.setEmployeeInfo();
employeeNames2 = e.getEmployeeNamesArrayList();
employeeWages2 = e.getWageArrayList();
// Local variables used in setEmployeePayroll.
double totalPay2 = 0.0;
double totalHours = 0.0;
double overTime = 0.0;
double overTime2 = 0.0;
System.out.println("Please enter ACME employee ID, the week they worked (1 or 2), and the number of hours worked. This information should be entered in the order the names were entered. Enter 0 when you are done inputing information.");
while(quit != 0)
{
quit = input.nextInt();
if(quit == 0)
{
break;
}
weeks = input.nextInt();
if(weeks == 1)
{
hoursWorked = input.nextDouble();
}
else if(weeks == 2)
{
hoursWorked2 = input.nextDouble();
}
/*
* I am checking to see if the employee is going to be paid for overtime and also calculating the pay for both weeks.
* 1) My first if statement indicates whether or not the employee worked over 40 in week one and week two.
* 2) My first else if statement indicates whether the employee works more than 40 hours in week two but not week one.
* 3) My second else if statement indicates whether the employee works more than 40 hours in week one but not in week two.
* 3) My third else if statement finally indicates that the employee worked over 40 hours in both week one and two.
*/
if(hoursWorked > 0 && hoursWorked <= 40 && hoursWorked2 > 0 && hoursWorked2 <= 40)
{
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay2 = totalHours * (employeeWages2.get(i - 1));
totalPay.add(totalPay2);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
else if(hoursWorked2 > 40 && hoursWorked > 0 && hoursWorked <= 40)
{
overTime2 = hoursWorked2 - 40;
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay2 = totalHours * (employeeWages2.get(i - 1)) + (overTime2 * 1.5);
totalPay.add(totalPay2);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
else if(hoursWorked > 40 && hoursWorked2 <= 40 && hoursWorked2 > 0)
{
overTime = hoursWorked - 40;
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay2 = totalHours * (employeeWages2.get(i - 1)) + (overTime * 1.5);
totalPay.add(totalPay2);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
else if(hoursWorked > 40 && hoursWorked2 > 40)
{
overTime = hoursWorked - 40;
overTime2 = hoursWorked2 - 40;
totalHours = hoursWorked + hoursWorked2;
hours.add(totalHours);
totalPay2 = totalHours * (employeeWages2.get(i - 1)) + (1.5 * (overTime + overTime2));
totalPay.add(totalPay2);
hoursWorked = 0.0;
hoursWorked2 = 0.0;
}
i = quit;
}
System.out.println();
System.out.println("Employee Number | Employee Name | Hours Worked | Total Pay");
for(int i = 0; i < e.getEmployeeNamesArrayList().size();)
{
System.out.println(String.format(employeeID, i + 1) + " | " + emID.get(i + 1) + " | " + hours.get(i + 1) + " | " + totalPay.get(i + 1));
}
}
}
EmployeeRecord:
import java.util.Scanner;
import java.util.ArrayList;
// ...javadoc...
public class EmployeeRecord
{
/*
* Creating the array and instance variables for EmployeeRecord consisting
* of TaxID numbers, Employee Names, Wages, Employee ID numbers and hours worked.
*/
ArrayList<String> employeeNames = new ArrayList<String>();
ArrayList<String> taxIDList = new ArrayList<String>();
ArrayList<Double> employeeWages = new ArrayList<Double>();
Scanner input = new Scanner(System.in);
private String employeeID = "%03d";
private String employeeFullName = " ";
private String taxID = " ";
private double wage = 0.0;
//Adding employees.
public void setEmployeeInfo()
{
System.out.println("Please enter the full names of each ACME employee, their employee tax ID, and their employee wage rate. Type 'Q Q' when you are done entering employee information.");
while(employeeFullName != "Q")
{
employeeFullName = input.next() + " " + input.next();
if(employeeFullName.equalsIgnoreCase("Q" + " " + "Q"))
{
break;
}
taxID = input.next();
wage = input.nextDouble();
employeeNames.add(employeeFullName);
taxIDList.add(taxID);
employeeWages.add(wage);
System.out.println("Employee ID | Employee Name | Tax ID | Wage");
for(int i = 1; i <= employeeNames.size(); i++)
{
System.out.printf(String.format(employeeID, i) + " | " + employeeNames.get(i - 1) + " | " + taxIDList.get(i - 1) + " | " + "%1.2f",employeeWages.get(i - 1));
System.out.println();
}
}
}
/**
* Creating a method that returns the employee ArrayList employeeName.
*/
public ArrayList<String> getEmployeeNamesArrayList()
{
return employeeNames;
}
/**
* Creating a method that returns the employee's Tax ID ArrayList taxIDList.
*/
public ArrayList<String> getTaxIdsArrayList()
{
return taxIDList;
}
/**
* Creating a method that returns the wages ArrayList
*/
public ArrayList<Double> getWageArrayList()
{
return employeeWages;
}
}
PayrollTester:
import java.util.Scanner;
// ...javadoc...
public class PayrollTester
{
public static void main(String[] args)
{
Payroll employeeComplete = new Payroll();
employeeComplete.setEmployeePayroll();
}
}
ArrayList index starts from 0. since your for loop start i = 0, you cannot do (i+1) in accessing arrayList elements.
emID.get(i + 1)
and also the size of emID is always 0 because you have just create new Arraylist but not added any objects to that list.
I can't get the while loop to work. The Program prompt user whether (s)he wants to continue, enter 0 toquit or any other integer to continue. If the user wants to c
ontinue, the program will loop back to themenu, otherwise, it will exit. Thus, you should have a sentinel-controlled loop that will end when a 0 is entered
import java.util.Scanner;
public class AdoptAPet
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int gender = 0;
double costAdoption = 0.0;
double costGenderSelect = 0.0;
double costAnyGender = 0.0;
double costProcessing = 0.0;
double total = 0.0;
int genderCounter = 0;
System.out.println("Choose from the following options: 1 for male, 2 for female, 3 for any");
while(gender != 0);//begin sentinel controlled while loop
{
System.out.print("Please choose the gender of the cat you wish to purchase:");
gender = input.nextInt();
if(gender < 0)
{
System.out.println("INVALID CHOICE! ");
System.out.print("enter 0 to quit: 0 or enter any other nunber to continue:");
gender = input.nextInt();
}
if(gender == 1)
{
costAdoption = 9.50;
costAdoption += costProcessing + 2.00;
total += costAdoption;
System.out.printf("Your Choice is: " );
System.out.printf("male and the total is $%.2f", total);
}
if(gender == 2)
{
costGenderSelect = 11.50;
costGenderSelect += costProcessing + 2.00;
total += costGenderSelect;
System.out.printf("Your Choice is: " );
System.out.printf("female and the total is $%.2f", total);
}
if(gender == 3)
{
costAnyGender = 9.50;
costAnyGender += costProcessing + 2.00;
total += costAnyGender;
System.out.printf("Your Choice is: " );
System.out.printf("Any gender and the total is $%.2f", total);
}
}
}
}
This line is responsible:
while(gender != 0);//begin sentinel controlled while loop
Look closely. There is a semi-colon at the end - that is the entire statement. The {} block that follows does not belong to the loop (and is executed exactly once).
Try dropping the ; from the end - we've fixed our while loop, but now the {} loop body doesn't execute at all. This is because gender is initialized with a value of 0. So to get our loop to execute at least once we need to either initialize gender to something else, or use a do-while loop.
Here is the modified code using a do-while.
import java.util.Scanner;
public class AdoptAPet
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int gender = 0;
double costAdoption = 0.0;
double costGenderSelect = 0.0;
double costAnyGender = 0.0;
double costProcessing = 0.0;
double total = 0.0;
int genderCounter = 0;
System.out.println("Choose from the following options: 1 for male, 2 for female, 3 for any");
do //begin sentinel controlled while loop
{
System.out.print("Please choose the gender of the cat you wish to purchase:");
gender = input.nextInt();
if(gender < 0)
{
System.out.println("INVALID CHOICE! ");
System.out.print("enter 0 to quit: 0 or enter any other nunber to continue:");
gender = input.nextInt();
}
if (gender == 1)
{
costAdoption = 9.50;
costAdoption += costProcessing + 2.00;
total += costAdoption;
System.out.printf("Your Choice is: " );
System.out.printf("male and the total is $%.2f", total);
}
if (gender == 2)
{
costGenderSelect = 11.50;
costGenderSelect += costProcessing + 2.00;
total += costGenderSelect;
System.out.printf("Your Choice is: " );
System.out.printf("female and the total is $%.2f", total);
}
if (gender == 3)
{
costAnyGender = 9.50;
costAnyGender += costProcessing + 2.00;
total += costAnyGender;
System.out.printf("Your Choice is: " );
System.out.printf("Any gender and the total is $%.2f", total);
}
} while(gender != 0); //end sentinel controlled while loop
}
}
Try this:
while(gender != 0);//<-- remove the semi colon,loop gets terminated by it
Also declare gender as:
int gender = -1;//<-- this will cause the loop to start