Java project method/if statement problems - java

I'm having a bit of problem with the getCost method in this code (I'll paste it below) and really need a response as soon as possible since this is due by midnight tomorrow. So the problem is that it says the things on the other side of the == are not valid, I mean the GRO, Gro, gro, SAL, Sal, and sal. For this code I have as user input a destination. Then I calculate the travel cost based on this input, and I'm also supposed to provide a free child ticket for every adult ticket, but I'm not sure how to do that at all. I'm sure what to do with the second method at all but it's required for the project so it has to be there. Thanks for any and all help.
import java.util.*;
public class HolidayTravel {
public static void main (String[] args) {
System.out.println("Thank you for choosing the Holiday Travel Special!");
System.out.println("All trips depart from and return to Raleigh, NC, and");
System.out.println("must take place between Nov 1, 2014 and Jan 15, 2015.");
System.out.println("When prompted, please enter your destination:");
System.out.println("GRO (Greensboro), SAL (Salisbury), or CLT (Charlotte),");
System.out.println("your departure/return dates, and the number of adult,");
System.out.println("student, and child ticketes you would like to purchase.");
System.out.println("Destination (GRO, SAL, CLT): ");
Scanner dest = new Scanner(System.in);
String destination = dest.nextLine();
System.out.println("Departure month (11, 12, 1): ");
Scanner mth = new Scanner(System.in);
int departureMonth = mth.nextInt();
System.out.println("Departure Day: ");
Scanner d = new Scanner(System.in);
int departureDay = d.nextInt();
System.out.println("Return month (11, 12, 1): ");
Scanner rM = new Scanner(System.in);
int returnMonth = rM.nextInt();
System.out.println("Return Day: ");
Scanner rD = new Scanner(System.in);
int returnDay = rD.nextInt();
System.out.println("Number of Adult Tickets: ");
Scanner aT = new Scanner(System.in);
int numberOfAdultTickets = d.nextInt();
System.out.println("Number of Student Tickets: ");
Scanner sT = new Scanner(System.in);
int numberOfStudentTickets = d.nextInt();
System.out.println("Number of Child Tickets: ");
Scanner cT = new Scanner(System.in);
int numberOfChildTickets = d.nextInt();
System.out.printf("Cost of tickts: %f\n", getCost (destination, numberOfAdultTickets, numberOfStudentTickets, numberOfChildTickets));
}
//Return true if the departure/return dates are valid dates between Nov 1 and Jan 15
//and the departure date occurs before or is the same as the return date
//Return false otherwise
//public static boolean areValidDates (int departureMonth, int departureDay, int returnMonth, int returnDay){
//}
//Calculates and returns cost of tickets based on destination, price of adult and child tickets,
//student discount, and with one free child ticket for each adult ticket purchase
//Throws an IllegalArgumentException if destination is invalid or number of tickets < 0
public static int getCost (String destination, int numberOfAdultTickets, int numberOfStudentTickets, int numberOfChildTickets) {
if (destination == GRO || Gro || gro){
double gCost = (numberOfAdultTickets*30.00) + (numberOfStudentTickets*(30.00-5.00)) + (numberOfChildTickets*20);
}else if(destination == SAL || Sal || sal){
double sCost = (numberOfAdultTickets*55.00) + (numberOfStudentTickets*(55.00-5.00)) + (numberOfChildTickets*45);
}else{
double cCost = (numberOfAdultTickets*60.00) + (numberOfStudentTickets*(60.00-5.00)) + (numberOfChildTickets*50);
}
}
}

You have to do your comparison like this:
public static int getCost (String destination, int numberOfAdultTickets, int numberOfStudentTickets, int numberOfChildTickets) {
if (destination.equals(GRO) || destination.equals(Gro) || destination.equals(gro)){
double gCost = (numberOfAdultTickets*30.00) + (numberOfStudentTickets*(30.00-5.00)) + (numberOfChildTickets*20);
}else if(destination.equals(SAL) || destination.equals(Sal) || destination.equals(sal)){
double sCost = (numberOfAdultTickets*55.00) + (numberOfStudentTickets*(55.00-5.00)) + (numberOfChildTickets*45);
}else{
double cCost = (numberOfAdultTickets*60.00) + (numberOfStudentTickets*(60.00-5.00)) + (numberOfChildTickets*50);
}
I hope GRO, Gro, gro, SAL, Sal and sal are variables of the type String. If not put "" between them, like this: "GRO" and so on...

Related

Brand new to Java, need some help restarting a while loop

I have just started learning Java in the last week or so and I'm creating a program that acts as a sales calculator that calculates commission.
My code is as follows:
import java.util.Scanner;
public class Application {
int itemOne;
int itemTwo;
int itemThree;
int itemFour;
final double baseCommission = 200;
final double itemOnePrice = 239.99;
final double itemTwoPrice = 129.75;
final double itemThreePrice = 99.95;
final double itemFourPrice = 350.89;
final double commissionPercentage = 0.09;
boolean startLoop = false;
public void start(){
while (startLoop = false);
{
//Welcome message
System.out.println("Welcome to Devon's Sales Calculator!");
//Defining new scanner
Scanner user_input = new Scanner(System.in);
//Getting user input for salesperson name along with number of items sold as well as assigning them to a variable
String salesman_name;
System.out.print("Insert salesperson name:\t");
salesman_name = user_input.next();
System.out.print("Enter number of first item sold:\t");
int first_item = user_input.nextInt();
System.out.print("Enter number of second item sold:\t");
int second_item = user_input.nextInt();
System.out.print("Enter number of third item sold:\t");
int third_item = user_input.nextInt();
System.out.print("Enter number of fourth item sold:\t");
int fourth_item = user_input.nextInt();
//Printing out the name of the salesmen, followed by the total price of items sold
System.out.println("Sales Person\t" + salesman_name);
System.out.println("Total price of first item sold\t" + first_item * itemOnePrice);
System.out.println("Total price of second item sold\t" + second_item * itemTwoPrice);
System.out.println("Total price of third item sold\t" + third_item * itemThreePrice);
System.out.println("Total price of fourth item sold\t" + fourth_item * itemFourPrice);
//Calculating total of all items sold
double finalPrice = first_item * itemOnePrice + second_item * itemTwoPrice + third_item * itemThreePrice + fourth_item * itemFourPrice;
//Calculating commission # 0,9%
System.out.println("Total commission earned\t" + finalPrice * commissionPercentage);
//Decision whether or not to restart the while loop
String decision;
System.out.println("Would you like to check another salesperson?");
decision = user_input.next();
if(decision == "yes"){
startLoop = false;
}
else if(decision == "no"){
startLoop = true;
}
}
}
}
Whenever I execute my while loop, it doesn't restart to choose another salesman. I'm probably doing something horribly wrong and my code formatting is probably horrible. Any help would be appreciated.
Get rid of the = false and the semicolon. So not:
while (startLoop = false);
{
System.out.println("foo");
}
which is equivalent to
while (startLoop = false) {
// do nothing
}
{
System.out.println("foo");
}
Instead do,
while (!startLoop) {
// do something here
}

Java.Lang.Stringindexoutofboundsexception index out of range (0)

each time the program tries to loop, the error "java.lang.stringindexoutofboundsexception" comes up and highlights
ki=choice.charAt(0);
Does anyone know why that happens?. I'm brand new to programming and this has me stumped. Thanks for any help. Any solution to this problem would be amazing.
import java.util.Date;
import java.util.Scanner;
public class Assignment2
{
public static void main(String Args[])
{
Scanner k = new Scanner(System.in);
Date date = new Date();
double Wine = 13.99;
double Beer6 = 11.99;
double Beer12 = 19.99;
double Beer24 = 34.99;
double Spirit750 = 25.99;
double Spirit1000 = 32.99;
int WinePurchase = 0;
double WineTotal=0.0;
double GrandTotal = 0.0;
double GST = 0.0;
String complete = " ";
String choice;
char ki = ' ';
double Deposit750 = 0.10;
double Deposit1000 = 0.25;
System.out.println("------------------------------\n" +
"*** Welcome to Yoshi's Liquor Mart ***\nToday's date is " + date);
System.out.println("------------------------------------\n");
do{
if(ki!='W' && ki!='B' && ki!='S')
{
System.out.print("Wine is $13.99\nBeer 6 Pack is $11.99\n" +
"Beer 12 pack is $19.99\nBeer 24 pack is $34.99\nSpirits 750ml is $25.99\n"+
"Spirits 100ml is $32.99\nWhat is the item being purchased?\n"+
"W for Wine, B for beer and S for Spirits, or X to quit: ");
}
choice = k.nextLine();
ki= choice.charAt(0);
switch (ki)
{
case 'W':
{
System.out.print("How many bottles of wine is being purchased: ");
WinePurchase = k.nextInt();
System.out.println();
WineTotal = Wine*WinePurchase;
GST = WineTotal*0.05;
WineTotal += GST;
System.out.println("The cost of "+WinePurchase+ " bottles of wine including" +
" GST and deposit is " + WineTotal);
System.out.print("Is this customers order complete? (Y/N) ");
complete = k.next();
break;
}
}
}while (ki!='X');
The error means there the index "0" is outside the range of the String. This means the user typed in no input, such as the case when you start the program and hit the enter key. To fix this, simply add the following lines of code:
choice = k.nextLine();
if(choice.size() > 0){
//process the result
}
else{
//ignore the result
}
Let me know if this helps!
As you pointed out, the problem is in:
choice = k.nextLine();
ki= choice.charAt(0);
From the docs nextLine(): "Advances this scanner past the current line and returns the input that was skipped."
So in case the user pressed "enter" the scanner will go to the next line and will return an empty String.
In order to avoid it, simply check if choice is not an empty string:
if (!"".equals(choice)) {
// handle ki
ki= choice.charAt(0);
}
Try this:
Your problem was with the Scanner (k) you need to reset it everytime the loop start over.
import java.util.Date;
import java.util.Scanner;
public class Assignment2
{
public static void main(String Args[])
{
Scanner k;
Date date = new Date();
double Wine = 13.99;
double Beer6 = 11.99;
double Beer12 = 19.99;
double Beer24 = 34.99;
double Spirit750 = 25.99;
double Spirit1000 = 32.99;
int WinePurchase = 0;
double WineTotal=0.0;
double GrandTotal = 0.0;
double GST = 0.0;
String complete = " ";
String choice;
char ki = ' ';
double Deposit750 = 0.10;
double Deposit1000 = 0.25;
System.out.println("------------------------------\n" +
"*** Welcome to Yoshi's Liquor Mart ***\nToday's date is " + date);
System.out.println("------------------------------------\n");
do{
if(ki!='w' && ki!='b' && ki!='s')
{
System.out.print("Wine is $13.99\nBeer 6 Pack is $11.99\n" +
"Beer 12 pack is $19.99\nBeer 24 pack is $34.99\nSpirits 750ml is $25.99\n"+
"Spirits 100ml is $32.99\nWhat is the item being purchased?\n"+
"W for Wine, B for beer and S for Spirits, or X to quit: ");
}
k= new Scanner(System.in);
choice = k.nextLine();
ki= choice.toLowerCase().charAt(0);
switch (ki)
{
case 'w':
System.out.print("How many bottles of wine is being purchased: ");
WinePurchase = k.nextInt();
System.out.println();
WineTotal = Wine*WinePurchase;
GST = WineTotal*0.05;
WineTotal += GST;
System.out.println("The cost of "+WinePurchase+ " bottles of wine including" +
" GST and deposit is " + WineTotal);
System.out.print("Is this customers order complete? (Y/N) ");
complete = k.next();
break;
}
if(complete.toLowerCase().equals("y"))
break;
}while (ki!='x');
}
}

Inheritance Error in java

This is super class of all,Employee class.
import java.util.Scanner;
import java.util.Calendar;
import java.util.*;
class Employee {
Scanner in = new Scanner(System.in);
Calendar cal = Calendar.getInstance();
String name;
String number;
int month;
int week;
double pay;
void load() {
System.out.println("Enter name of employee");
name = in.nextLine();
System.out.println("Enter social security number");
number = in.nextLine();
System.out.println("Enter employee's birthday month(1-12)");
month = in.nextInt();
System.out.println("Enter employee's birthday week(1-4)");
week = in.nextInt();
}
public String toString() {
return "employee : " + name + " social security number : " + number
+ " paycheck : $" + pay;
}
void getBonus() {
int mont = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
if (month == mont + 1 && week == (day / 7) + 1)
pay = pay + 100;
}
}
This is subclass of employee .
import java.util.Scanner;
class Hourly extends Employee {
Scanner in = new Scanner(System.in);
double pay;
int hpay;
int hours;
void load() {
System.out.println("Enter hourly pay");
hpay = in.nextInt();
System.out.println("Enter no. of hours worked last week");
hours = in.nextInt();
}
double getEarnings() {
if (hours > 40)
pay = 1.5 * (hours - 40) * hpay + hpay * 40;
else
pay = hpay * hours;
return pay;
}
}
There are 2 more subclasses like these and finally i have test file.
import java.util.Scanner;
class driver {
public static void main(String args[]) {
int i;
Scanner in = new Scanner(System.in);
System.out.println("Enter no. of employees");
int a = in.nextInt();
for (i = 1; i <= a; i++) {
System.out
.println("Enter type : Hourly(1),Salaried(2),Salaried plus commision(3)");
int b = in.nextInt();
if (b == 1) {
Hourly h = new Hourly();
h.super.load();// error cannot find symbol h
h.load();
h.getEarnings();
}
if (b == 2) {
Salaried s = new Salaried();
s.load();
s.getEarnings();
}
if (b == 3) {
Salariedpluscommision sp = new Salariedpluscommision();
sp.super();// error that super should be in first line but then
// where can i define sp
sp.super.load();// cannot find symbol sp
sp.load();
sp.getEarnings();
}
}
}
}
I have got 3 errors in these codes and as i am beginner i don't know how can i solve these errors.
My program takes the employee's details from user and calculate paycheck of that employee.
Also,I am confused in how can i print all employee's paychecks at last after user have completed giving input of all employee's details.Can i do these with an array ?
But first,i have to remove these errors and also suggest my which topics are weak which i should focus more.
Thank you in advance
You appear to be a bit confused about the keyword super.
In the code
Salariedpluscommision sp=new Salariedpluscommision();
sp.super();//error that super should be in first line but then where can i define sp
sp.super.load();//cannot find symbol sp
sp.load();
sp.getEarnings();
the compiler is telling you that super cannot be used where you're using it.
Most likely you just don't need it at all in the driver code and the code
Salariedpluscommision sp=new Salariedpluscommision();
sp.load();
sp.getEarnings();
will do what you thought you needed these calls for.
Similarly, in the earlier code, you can likely just delete the line
h.super.load();// error cannot find symbol h
As it's coded however, you might need to call some superclass methods from your subclasses, which is what the keyword is for.
In Hourly and likely the other subclasses, you probably want to call the Employee load method within the subclass load method:
void load(){
super.load();
System.out.println("Enter hourly pay");
hpay = in.nextInt();
System.out.println("Enter no. of hours worked last week");
hours = in.nextInt();
}
which appears to be what you were trying for with some of the non-compiling code in driver.
Several suggestions:
Make Employee an abstract class and add public abstract getEarnings(); method
Simplify your Driver routine to use switch / case rather than multiple if statements
Create an ArrayList to collect a list of all employees
Use the "type" of employee to create the right kind ... use the same variable name though
After creating the "right kind" of employee, load it and get the earnings
.... (print out the earnings?
Just create objects .. don't use "super
Consider the following for Driver:
import java.util.ArrayList;
import java.util.Scanner;
class driver {
public static void main(String args[]) {
ArrayList<Employee> employees = new ArrayList<Employee>();
Employee emp;
double earnings;
int i;
Scanner in = new Scanner(System.in);
System.out.println("Enter no. of employees");
int a = in.nextInt();
for (i = 1; i <= a; i++) {
System.out.println("Enter type : Hourly(1),Salaried(2),Salaried plus commision(3)");
int b = in.nextInt();
emp = null;
switch (b) {
case 1:
emp = new Hourly();
break;
case 2:
emp = new Salaried();
break;
case 3:
emp = new Salariedpluscommision();
break;
default:
System.out.println("You entered an invalid employee type.");
break;
}
if (emp != null) {
emp.load();
earnings = emp.getEarnings();
employees.add(emp);
System.out.println("Earnings are: " + earnings + "for " + emp.getName());
}

Code seems to skip over if or for loop

When I enter input that satisfies everything and doesn't trigger any of my errors, the program just exits after last input like it is skipping over the for or if loop.
Also after System.out.printf("Enter the name of your second species: "); it won't allow for any input, it just skips to the next prompt. I'm not sure why that is. The section above it asking for the first species' info works fine.
import java.util.Scanner;
public class HW2johnson_pp1 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("Please enter the species with the higher" +
" population first\n");
System.out.printf("Enter the name of your first species: ");
String Species1 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop1 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth1 = keyboard.nextInt();
System.out.printf("Enter the name of your second species: ");
String Species2 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop2 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth2 = keyboard.nextInt();
if (Pop2 > Pop1) {
System.out.printf("The first population must be higher. \n");
System.exit(0);
}
Species input1 = new Species();
input1.name = Species1;
input1.population = Pop1;
input1.growthRate = Growth1;
Species input2 = new Species();
input2.name = Species2;
input2.population = Pop2;
input2.growthRate = Growth2;
if ((input1.predictPopulation(1) - input2.predictPopulation(1)) <=
(input1.predictPopulation(2) - input2.predictPopulation(2))){
System.out.printf(Species2 + " will never out-populate " +
Species1 + "\n");
}
else {
for (int i = 0; input2.predictPopulation(i) <=
input1.predictPopulation(i); i++) {
if (input2.predictPopulation(i) == input1.predictPopulation(i)) {
System.out.printf(" will out-populate \n");
}
}
}
}
}
This for the predictPopulation():
public int predictPopulation(int years)
{
int result = 0;
double populationAmount = population;
int count = years;
while ((count > 0) && (populationAmount > 0))
{
populationAmount = (populationAmount +
(growthRate / 100) * populationAmount);
count--;
}
if (populationAmount > 0)
result = (int)populationAmount;
return result;
}
This is because you never print anything after Species 2 overtakes Species 1, except in the very special case that Species 2 and Species 1 have exactly the same population in some year.
This is because, when you enter Species 1's growth rate, you enter an integer, and then press Enter. keyboard.nextInt() swallows the integer, but leaves the newline on the input-buffer, so the subsequent keyboard.nextLine() thinks there's an empty line there waiting for it.

how to check the int range in java and limit it only 5digits

Please help with my assignment. Here is the question:
Create a separate test driver class
called TestEmployeePayroll that will
test the EmployeePayroll class by
performing the following:
Prompt the user to enter the
employees’ ID number, First name, Last
name, Pay Category and Hours worked
(one at a time).
The user entry for employees ID
number must be exactly 5 digits long.
The user entry for Category must only
be accepted if it is in the range 1
to 4.
The user entry for Hours worked
must only be accepted if it is the
range 1 to 80.
This is what I did till now:
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args){
EmployeePayRoll obj1 = new EmployeePayRoll();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Employee ID number: "+ " ");
String EmployeeID = input.nextLine();
//How to check the range here if int is 5 digits long or not ?
System.out.println("Enter the first Name: "+ " ");
String FirstName = input.nextLine();
System.out.println("Enter Last Name: "+ " ");
String LastName = input.nextLine();
System.out.println("Enter the Pay Category: "+ " ");
double PayCategory = input.nextDouble();
System.out.println("Enter the number of hours worked: "+ " ");
double HoursWorked = input.nextDouble();
}
}
You will probably want to use Integer.parseInt().
You can count the length of a String and then convert it to number, Oli Charlesworth told you how to convert it, or you can measure the number. It depends on what you want. Is 012345 a valid ID? It's a 6 char String but it is less than the biggest 5 digits number.
I think you almost got it...
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args){
// ... get the values, as you are doing already
// validate input
int employeeIdAsInteger = validateAndConvertEmployeeId(EmployeeId);
int payCategoryAsInteger = validateAndConvertPayCategory(PayCategory);
// ... and so on
}
private int validateAndConvertEmployeeId(String employeeId) {
// The user entry for employees ID number must be exactly 5 digits long.
if (employeeId == null || employeeId.trim().length() != 5) {
throw new IllegalArgumentException("employee id must be exactly 5 digits long");
}
// will throw an exception if not a number...
return Integer.parseInt(employeeId);
}
// ...
}
Depending on your objectives & constraints, you could look into the Pattern class and use a regular expression.
You can check for conditions like this.
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args) {
TestEmployeePayRoll obj1 = new TestEmployeePayRoll();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Employee ID number: " + " ");
String EmployeeID = input.nextLine();
if (EmployeeID.trim().length() != 5) {
System.out.println("--- Enter valid Employee ID number ---");
}
System.out.println("Enter the first Name: " + " ");
String FirstName = input.nextLine();
System.out.println("Enter Last Name: " + " ");
String LastName = input.nextLine();
System.out.println("Enter the Pay Category: " + " ");
double PayCategory = input.nextDouble();
Double pay = new Double(PayCategory);
if (pay.isNaN()) {
System.out.println("***** Enter a valid Pay Category *****");
}
if (!(PayCategory >= 0 && PayCategory <= 5)) {
System.out.println(" --- PayCategory must be between 0 and 5");
}
System.out.println("Enter the number of hours worked: " + " ");
double HoursWorked = input.nextDouble();
Double hours = new Double(HoursWorked);
if (hours.isNaN()) {
System.out.println("--- Enter a valid hours value ----");
} else {
if (!(HoursWorked >= 1 && HoursWorked <= 80)) {
System.out.println("--- Enter value between 1 and 80 ---");
}
}
}
}

Categories

Resources