Unreachable code, compilation error vicious circle - java

So I have made a programme that calculates the cost of of a ticket based on a number of factors I'll post the question i got below
Create a program that given a number of tickets (maximum of 10),
the type of ticket (return, one way), the passenger type (under 10, under 16,
student, over 60, other), the selected route, and the starting and finishing
stops (in the form of a number where n denotes stopn ),
calculates the total cost for the journey.
The cost of each ticket should be calculated as follows:
• The cost per mile is 50p;
• Under 10 travel free when accompanied by an adult;
otherwise, a discount of 75% is applied;
• Under 16 get a 50% discount;
• Students get a 25% discount;
• Over 60’s get a 60% discount.
Train routes should be expressed in the format:
int [n] route = {stop2 , stop3 , ... stopNPlusOne};
Example:
int [4] route1 = {3, 5, 2, 6};
denotes a route with 5 stops:
the distance between stop one and two is 3 miles,
between stop two and three is 5 miles,
between stop three and four is 2,
and between stop four and five is 6.
My code is as follows
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of Tickets (Max 10): ");
int numberOfTickets = input.nextInt();
if (numberOfTickets > 10) {
System.out.println("Please choose less than 10 tickets");
} else {
double cost = route();
double totalCost = (cost * numberOfTickets);
System.out.println("");
System.out.printf("Your total cost is:", totalCost);
}
}
// DECLARE A NEW METHOD THAT CALCULATES THE DISTANCES TRAVELLED
public static double route() {
Scanner input = new Scanner(System.in);
int[] route = { 7, 12, 13, 17, 22, 26 }; // miles between each stop
System.out.println("Enter the first station number(0 - 5): ");
int firstStation = input.nextInt();
System.out.println("Enter the last station number(0 - 5): ");
int lastStation = input.nextInt();
int totalMiles = 0;
for (int i = firstStation; i < lastStation; i++) {
totalMiles = totalMiles + route[i]; // Total miles
}
System.out.println(totalMiles);
double cost = totalMiles * 0.5; // (* 0.5) because it's 50p per mile.
System.out.println("The initial cost is £" + cost);
System.out.println("Please enter your age");
int age = input.nextInt();
double totalCost = 0;
int adults = 0;
return adults;
{
{
if ((age < 10) && (age > 0)) {
cost = (cost * 0.25);
} else if ((age < 16) && (age >= 10)) {
cost = (cost * 0.5);
} else if (age > 60) {
cost = (cost * 0.4);
}
System.out.println("Are you a student, if yes enter 1 if not enter 2");
int studentPass = input.nextInt();
boolean Student = false;
if (studentPass == 1)
{
Student = true;
}
if (studentPass == 2) {
adults++;
}
return cost;
}
}
}
}
}
The issue is there is an error on the last curly bracket and so when i delete it everything from return adults and down is said to be unreachable code.
Apologies for the vast amount of text in the question. I'm in java by the way.

The problem is that you have multiple returns in the same function. When a return executes the function exits meaning that the code below will never be able to be run and thus it is unreachable.
So in this:
public int function(){
value = 0
//do stuff
return value
//do more things
}
"do more things: will never be able to be run because the function stops running as soon as return value is encountered. This code is said to be unreachable.
Put your code in multiple functions, each with only one return, and then call those functions from your main or wherever you want to use them as necessary

Related

Unable to add 20 "points" for reward program for above 3 beverages

I'm trying to add 20 "points" for every beverage (or drink) that a customer had the previous week for a rewards program after 3 beverages. However, I can't seem to add 20 points for every beverage past 3. It just adds 20 additional points, and then stops adding after that.
For example, if a customer had 4 beverages last week, then they should have 50 reward points; 70 reward points for 5 beverages, 90 points for 6 beverages, and so on. What my program is currently doing (or has done) is gone to 50 or 70 and then stayed the same (it's at 50 currently), no matter the number inserted, it's gone negative and subtracts 20, or infinitely loops without a break.
The numbers 1-3 are already taken for having 5 points, 15 points, and 30 points, respectively.
import java.util.Scanner;
public class RedDevilCoffeeRewards
{
public static void main(String[] args)
{
// Create Scanner
Scanner scanner = new Scanner(System.in);
// Ask user how many beverages (or drinks) they bought last week
System.out.println("How many beverages did you purchase last week");
// Allows user input for amount of beverages bought last week
int beverages = scanner.nextInt();
int beverages4 = 50;
int beveragesaddpoints = 20;
int beveragepointtotal = beverages4 + beveragesaddpoints;
//int beveragesmorethan4= beverages4 + 20;
for (int beverages4orhigher = beveragepointtotal; beverages4 >= 4; ++beverages4)
{
if (beverages >= 4)
{
beveragepointtotal += beveragesaddpoints;
System.out.println("You have earned " + beverages4 + " points");
break;
}
}
The problem with your code is in the for loop that you have mentioned. You have declared a variable beverages4orhigher which is not used in the loop and then you are breaking out of the loop based on the beverages value which will be always be true in case the value is more than 4.
ii) You are printing the value of beverages4 and not beverageinTotal that should be printed.
You need to rectify these 2 changes.
public class RedDevilCoffeeRewards {
public static void main(String[] args) {
// Create Scanner
Scanner scanner = new Scanner(System.in);
// Ask user how many beverages (or drinks) they bought last week
System.out.println("How many beverages did you purchase last week");
// Allows user input for amount of beverages bought last week
int beverages = scanner.nextInt();
int beverages4 = 50;
int beveragesaddpoints = 20;
int beveragepointtotal = beverages4 + beveragesaddpoints;
// int beveragesmorethan4= beverages4 + 20;
int points = 0;
if (beverages == 1) {
points = 5;
} else if (beverages == 2) {
points = 15;
} else if (beverages == 3) {
points = 30;
} else {
points = 30;
beveragepointtotal = beverages - 3;
for (int i = 0; i < beveragepointtotal; i++) {
points += 20;
}
}
System.out.println("You have earned " + points + " points");
}
}
and the sample output is
How many beverages did you purchase last week
6
You have earned 90 points

Is there a code on java that allows for two if statements with one independent statement for Shipping Charges?

I am very new to java and have been stuck on a program that I've been trying to create. For background knowledge purposes, the program is for a company called "Ship It" which is a package shipping company. The user enters the weight of the package, and the distance it will travel. Depending on the weight, the company charges a fee per 200 miles.
0 < weight <= 3 pounds $1.00 charge
3 < weight <= 6 pounds $2.00 charge
6 < weight <= 10 pounds $3.00 charge
10 < weight <= 20 pounds $4.00 charge
20 < weight <= 30 pounds $5.00 charge
So far, this is the code I have:
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
//Variables
double costWithoutCharge = 0, weight, distance = 0;
//Introduction to ShipIt
System.out.print("\t\t******Welcome to ShipIt******\n");
System.out.print("***We are a low-charge, secure shipping company for packages" +
"up to 30 pounds***");
//User Enters Weight of Package
System.out.print("\n\nEnter the weight of the package (1.0 - 30.0 pounds): ");
weight = kb.nextDouble();
System.out.print("");
// User Enters distance the package will travel
System.out.print("Enter the miles to the destination (1 - 2000 miles): ");
distance = kb.nextInt();
System.out.print("");
//Weight If-else Statement
if (weight >30.0)
System.out.println ("\nSorry, you have entered invalid data - program terminated");
if (weight >30.0)
System.exit((int) weight);
//Distance Restriction if-else
if (distance >2000)
System.out.println ("\nSorry, you have entered invalid data - program terminated");
if (distance >2000)
System.exit((int) distance);
costWithoutCharge = distance / 200;
//If else
if (weight <0 || weight <=3)
{
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*1.00);
}
else if (weight <3 || weight <= 6)
{
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*2.00);
}
else if (weight <6 || weight <= 10)
{
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*3.00);
}
else if (weight <10 || weight <= 20)
{
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*4.00);
}
else {
System.out.println ("The cost to ship the package is: "+ "$" + (costWithoutCharge)*5.00);
}
kb.close();
}
}
As of now, if I put a value like 1001, the cost to ship is $15.015, but it should be $18 since the charge is multiplied per 200 miles. I am on the fence if I need to do a new equation for the charge per 200 miles dilemma or if it can be supported with another if-statement?
I feel as though I have tried everything but I can't seem to solve this ): I am in dire need of help! Please!
The weight is missing from your example.
it sounds like in your example you have:
distance 1001
weight between 6 and 10, resulting in a $3 charge per "beginning 200 miles"
From your code, 15.015 gets returned.
It appears you want to calculate the "beginning 200 miles", so you could achieve that by rounding up:
costWithoutCharge = Math.ceil( distance / 200 );
On another note, you may want to remove the common parts from your if/then/else block. That is, only perform the calculation but not the System.out.println inside each clause.
First
if (weight <0 || weight <=3)
should be
if (0 < weight && weight <=3)
However the code should be easier to maintain, use a table of limits:
double[][] weightsAndCharges = {
{3, 1.00},
{6, 2.00},
{10, 3.00},
{20, 4.00},
{30, 5.00}
};
double charge = 10.00;
for (double[] weightAndCharge : weightAndCharges) {
if (weight <= weightAndCharge[0]) {
charge = weightAndCharge[1];
break;
}
}
System.out.printf("The cost to ship the package is: $%0.2f%n", charge*distanceRatio);
The answer is some basic math.
What you are thinking of is a combinatorial explosion: If you layer a whole batch of if/elseif statements inside each of your weight if statements for e.g. if (miles < 200) ... else if (miles >= 200 && miles < 400) - then think of it in dimensions: You have the 'miles' dimension which currently is adding 10 options (1-200, 200-399, 400-599, etc), the weight dimension which adds 5.
The amount of ifs you'd need here is then A*B: 50 ifs.
That's a ton, and clearly not what you want.
Math to the rescue!
You really just want to calculate costPerSegment * segments.
Calculate those 2 values individually, and now it's just A + B: 15 ifs. Given that you can actually use math itself to turn the miles number into the # of segments you need to charge (it's just division by 200 for the miles part, no lookup table involved), we're down to 5 ifs.
Note also your code is buggy. Your weight if statement have their > and < reversed. But the else if hides the problem. I fixed that problem in the snippet below.
double costPerSegment;
if (weight <=3) {
costPerSegment = 1.0;
} else if (weight <= 6) {
costPerSegment = 2.0;
} else if (weight <= 10) {
costPerSegment = 3.0;
} else if (weight <= 20) {
costPerSegment = 4.0;
} else {
costPerSegment = 5.0;
}
// Casting a positive double to an int automatically rounds down.
int segments = (int) miles / 200;
double cost = costPerSegment * segments;
This line is causing the problem for input distance 1001
costWithoutCharge = distance / 200; // result = 5,005
As far as I understood you want to have here just 5
So the simpliest solution would be to declare costWithoutCharge as int
and than
costWithoutCharge = (int) distance / 200; // result = 5
Or if you want to keep costWithoutCharge as double you can use Math lib to round it
costWithoutCharge = Math.round(distance / 200); // result = 5

How do I get my code to process a given minimum value AND a value if < than given minimum

I am a Java newbie and have been working on this program for about a month. My program is a graduation planner that shows the student how much time and money it would take to finish a college degree. I would like my program to be able to recognize that the minimum # of CUs could be < than 12 if the student only has 6 or so CUs left until graduation, but I also need it to recognize if I enter a letter or negative number which I somehow managed to pull off at the top of the code. I tried to use sum == sum which isn't giving me the desired output. I think I need to put the while (loop) somewhere in there.
package gradplanner13;
import java.util.ArrayList;
import java.util.Scanner;
public class GradPlanner13 {
public static void main(String[] args) {
int sum = 0;
Scanner input = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<>();
boolean loop = true;
System.out.println("Enter the individual CUs for your remaining courses. Enter 0 when done entering your individual CUs.");
while (loop) {
System.out.print("Enter CUs for individual course then press enter: ");
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only positive numbers are valid inputs. Please try again. ");
continue;
}
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only postive numbers are valid inputs. Please try again.");
continue;
}
int check = input.nextInt();
input.nextLine();
if (check == 0) {
loop = false;
continue;
} else if (check < 0) {
System.out.println("CU values must be positive. Try again.");
continue;
}
array.add(check);
}
for (Integer CUs : array) {
sum += CUs;
}
System.out.println("Total number of CUs for all courses: " + sum);
double rounded = 0;
do {
System.out.print("How many CUs you are planning to take each term: ");
rounded = input.nextInt();
if (sum == sum) {
break;
}
if (rounded < 12 || rounded > sum) {
System.out.println("Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 : ");
}
} while (rounded < 12 || rounded > sum);
double numTermsToCompletion = Math.ceil(sum / rounded);
System.out.println("Number of terms to completion: " + numTermsToCompletion);
System.out.println("Tuition cost based on number of terms to completion: $" + (numTermsToCompletion * 2890));
System.out.println("Number of months to completion: " + (numTermsToCompletion * 6));
}
}
The below code is the section that I think I am having trouble with because I need it to recognize that sometime a student may not have the minimum (12) CUs left and I would like it to check to make sure the minimum is met or recognize that less than the minimum is left and still process the input. I tried to reuse while (loop) cause I know that part of the program responds correctly when I try to enter a letter or negative number at the beginning of the code, but I obviously was not implementing the loop correctly when I tried to put it on the below code, the program runs but doesn't produce anything when it gets to that point in the code. It just runs and doesn't produce any errors. In summary, I would appreciate some assistance getting my code to realize that a student may not have the minimum CUs left (12) and may need < than that to graduate, but also not accept negative numbers or letters as input.
do {
System.out.print("How many CUs you are planning to take each term: ");
rounded = input.nextInt();
if (sum == sum) {
break;
}
if (rounded < 12 || rounded > sum) {
System.out.println("Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 : ");
}
} while (rounded < 12 || rounded > sum);
So I moved sum == sum and I am a little closer to where I need to be. I still need to do some research because I am how getting the statement that tells me that I need to have a minimum of 12, but it still gives me the correct output.
do {
System.out.print("How many CUs you are planning to take each term: ");
rounded = input.nextInt();
if (rounded < 12 || rounded > sum) {
System.out.println("Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 : ");
}
if (sum == sum) {
break;
}
} while (rounded < 12 || rounded > sum);
This is the output:
Total number of CUs for all courses: 8
How many CUs you are planning to take each term: 8
Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 :
Number of terms to completion: 1.0
Tuition cost based on number of terms to completion: $2890.0
Number of months to completion: 6.0
BUILD SUCCESSFUL (total time: 12 seconds)
Ok. From the recommendations I have received, I rethought the process and rewrote some of the code and it works a lot better. The problem now is if the user enters 0 from the beginning, this is the output:
Enter the individual CUs for each individual remaining course. Enter 0 when done entering your individual CUs for each course.
Enter CUs for individual course then press enter: 0
Total number of CUs for all courses: 0
Number of terms to completion: 1
Tuition cost based on number of terms to completion: $2890
Number of months to completion: 6
BUILD SUCCESSFUL (total time: 2 seconds)
If you have 0 CUs left, you shouldn't have any terms left. It looks like I need to either change where my loop is false, or do something similar like I did here:
if (sum >= 12) {
do {
System.out.print("How many CUs you are planning to take each term? Minimum of 12 CUs required per term: ");
numOfCUs = input.nextInt();
} while (numOfCUs < 12);
numTermsToGraduation = (int) Math.ceil(sum / (double) numOfCUs);
Below is the complete new code:
System.out.println("Enter the individual CUs for each individual remaining course. Enter 0 when done entering your individual CUs for each course.");
package gradplanner13;
import java.util.ArrayList;
import java.util.Scanner;
public class GradPlanner13 {
public static void main(String[] args) {
int sum = 0;
Scanner input = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<>();
boolean loop = true;
// Student enters the individual credits for each course remaining in their degree program
System.out.println("Enter the individual CUs for each individual remaining course. Enter 0 when done entering your individual CUs for each course.");
// loop checks to make sure inputs are positive numbers
while (loop) {
System.out.print("Enter CUs for individual course then press enter: ");
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only positive numbers are valid inputs. Please try again. ");
continue;
}
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only postive numbers are valid inputs. Please try again.");
continue;
}
int check = input.nextInt();
input.nextLine();
if (check == 0) {
loop = false;
continue;
} else if (check < 0) {
System.out.println("CU values must be positive. Try again.");
continue;
}
// Calculates inputs from user
array.add(check);
}
for (Integer CUs : array) {
sum += CUs;
}
System.out.println("Total number of CUs for all courses: " + sum);
int numOfCUs = 0;
int numTermsToGraduation = 0;
if (sum >= 12) {
do {
System.out.print("How many CUs you are planning to take each term? Minimum of 12 CUs required per term: ");
numOfCUs = input.nextInt();
} while (numOfCUs < 12);
numTermsToGraduation = (int) Math.ceil(sum / (double) numOfCUs);
} else {
numOfCUs = sum;
numTermsToGraduation = 1;
}
System.out.println("Number of terms to completion: " + numTermsToGraduation);
System.out.println("Tuition cost based on number of terms to completion: $" + (numTermsToGraduation * 2890));
System.out.println("Number of months to completion: " + (numTermsToGraduation * 6));
}
}
From what I could tell, you are trying to use "sum == sum" to tell you if the input value is an negative number or a letter. This is not correct, as sum==sum will always return true.
For checking if it is a number is positive, you should just use sum > 0.
As for checking if its actually a letter, and not a number, this is handled by your scanners when you check if the input is a number (hasNextInt).
It looks like you are using if (sum == sum) {...} to error check the value of sum. That is not what you want to do, because it is always going to equate to true. What you want to do is use a try {...} catch (InputMismatchException e) {...}. In your case, it would be set up as follows:
...
System.out.println("Enter the individual CUs for your remaining courses. Enter 0 when done entering your individual CUs.");
int exception = 1;
while (exception = 1) {
try {
int someNum = input.nextInt();
...
}
catch (InputMismatchException e) {
exception = 1;
System.out.println("Please enter the correct data type!");
}
}
...
At the first moment the InputMismatchException is thrown, the program will execute the code in the catch block.

Java how to compute average scores using loops

I need to write a program in Java that computes the average score for 4 students. The student will put in their 4 scores, and once they are done they will input -1 to compute the average. Once this is done the program needs to move onto student 2 and so on. At the end it is supposed to display the highest average from the 4 student average test scores. Here is what it should look like when it is run:
Student 1
Enter your score: 100
Enter your score: 90
Enter your score: 80
Enter your score: 70
Enter your score: -1 * once the student enters -1 it should compute average
Average Score = 85.
Student 2
Enter your score: 90
ETC
ETC
The problem with my code is that the average is only correct for the first student. When I input -1 to get the average for the second student, the calculation is incorrect. We are only allowed to use loops. The only hints I was given were that we are supposed to write an outer loop that iterates 4 times, write an inner loop that loops as long as the student has scores to enter, inside the inner loop prompt the user to enter their last score or -1 to compute average. I don't want you guys to do the project for me but to just set me in the right direction. I feel like I am not using the right loop.
import java.util.Scanner;
public class TestScore
{
public static void main(String[]args)
{
double score = 0;
double totalScore = 0;
double count = 0;
double average = 0;
Scanner input = new Scanner(System.in);
System.out.println("Student 1");
System.out.printf("Enter Your Score: ");
score = input.nextDouble();
while (score != -1){
System.out.printf("Enter Your Score: ");
totalScore = totalScore + score;
score = input.nextDouble();
count++;
average = totalScore / count;
if (score == -1){
System.out.printf("Average Score = %.2f\n ",average);
count = 0;
score = 0;
totalScore = 0;
average = 0;
System.out.println("Student 2");
System.out.printf("Enter Your Score: ");
score = input.nextDouble ();
count++;
average = totalScore / count;
}
}
}
}
You haven't explicitly asked a question so I'll try and comply to the "set me in the right direction" part.
I'd suggest re-formatting the loop structure to a cleaner one, like this:
double total;
for(int student = 1; student <= 4; student++) {
System.out.printf("Student %d\n", student);
double sum = 0, count = 0;
while(true) {
System.out.printf("Enter your score: ");
double input = scanner.nextDouble();
if(input == -1) break;
sum += input;
count++;
}
total += sum;
System.out.printf("Average: %.2f\n", sum / count);
}
System.out.printf("Total: %.2f\n", total);
Hope that's enough to give you some pointers.
edit: forgot to take care of total
So, you wish to iteratively go through all the input and just remember the maximum one. Make an integer variable max and after each student, just change it if needed. (It's zero by default jn Java)
As for the calculation for each student, you shouldn't be checking for the failed " score != - 1" condition in each iteration. Instead, you should do the final calculations after the while loop. (average, possible update of the maximum, resetting the variables, etc. )
You also need the outer loop (in the stated code, these calculations are done for one student only) which you would control in a different manner.
Also, if you need to use only 4 grades, you might want to consider using the for loop.
You can try with this :D
public static void main (String[] args) throws java.lang.Exception
{
double average = 0;
double i = 0;
int student = 0;
boolean flag = true;
Scanner input = new Scanner(System.in);
while(flag)
{
System.out.printf("Student: ");
System.out.println(student);
System.out.print("Enter Your Score: ");
double score = input.nextDouble();
if(score!=-1){
average=average+score;
i=i+1;
}
if(score==-1){
System.out.printf("Average: ");
System.out.println(average/i);
//reset values
average = 0;
i = 0;
student=student+1;
}
if(score==-2){
//you need break the while in some moment.
flag = false;
}
}
}

Check if integers within an array are within the range

Basically, the program I am supposed to write is to get the energy usage from the customer for 12 months and then output the total usage, price for two tariffs (the formulas are included in the code) and say which tariff is cheaper. But it also has to check whether the input for each of those 12 months is within the range (greater than "0" AND less or equal to "1000").
I have found a fairly easy(?) way to do it using arrays, however I have no idea how to check whether each one of the integers scanned to be in that array are actually within the range 0 < int <= 1000
If the integer is less than 0 or greater than 1000, the program has to output a line "Please enter a valid amount" and ask for the same integer again, so that it doesn't store the wrong value, if it makes sense?
import java.util.Scanner;
public class EnergyConsumptionExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int total_usage;
float t1_cost, t2_cost;
final int MAX_USAGE = 1000, MIN_USAGE = 0;
int[] energyCons = new int[12];
for (int month = 0; month < energyCons.length; month++) {
System.out.print("Please enter the monthly kWh usage for month ");
System.out.print((month + 1) + ": ");
energyCons[month] = scan.nextInt();
}
int totalCons = 0;
for (int month = 0; month < energyCons.length; month++) {
totalCons += energyCons[month];
}
System.out.println();
System.out.println("Total usage for the year was " + totalCons + " kWh");
t1_cost = (float) (totalCons * 0.1);
t2_cost = (float) ((totalCons * 0.09) + 50);
System.out.println("Using tariff one, the cost is: " + t1_cost);
System.out.println("Using tariff two, the cost is: " + t2_cost);
System.out.println();
if (t1_cost > t2_cost) {
System.out.println("Tariff two would be cheaper for this customer.");
} else {
System.out.println("Tariff one would be cheaper for this customer.");
}
}
}
Change your input reading loop to something like this:
for (int month = 0; month < energyCons.length; month++) {
System.out.print("Please enter the monthly kWh usage for month ");
System.out.print((month + 1) + ": ");
int inputValue = scan.nextInt();
while (inputValue < 0 || inputValue > 1000) {
System.out.println("Please enter a valid amount: ");
inputValue = scan.nextInt();
}
energyCons[month] = inputValue;
}

Categories