Code a complete Java program to the following:
if it is a red light violation, then the fine is 1.75 % of the driver annual salary
if it is a speeding violation, then the fine is 1.2 %of the annual salary plus .5% of the salary for every 1 mile/hour over the speed limit.
What you need to do?
prompt user/officer to enter the full name of the driver
prompt officer to enter his/her full name.
prompt user/officer to enter annual salary of the driver.
prompt the officer to enter the type of violation (1 for red light or 2 for speeding)
if speeding then prompt user to enter how many miles/hour over speed limit.
evaluate with a set of if...else how much fine should be assessed, then print a full report including:
name of officer
name of driver
annual salary
violation type (you need to spell it out not just 1 or 2. (Red Light or Speeding)
amount of fine assessed (print a $ sign and round to two decimals)
Also, you must consider the following:
your program must not accept any code other than 1 or 2 for violation type.
your input must be handled by different methods and not in main()
evaluating the fine must be handled in a method of its own.
report must be handled by a different method.
the whole program must repeat for a new driver.
Extra credits: develop your own solution when a driver is subject to both violation…caught speeding and passing when red
Here is my code:
package FinFines_
import java.util.Scanner;
/*
* Description: This program assesses fines for traffic violations.
*/
public class FinFines_
{
static Scanner get = new Scanner(System.in);
//declarations:
static double mph = 0;
static double salary = 0;
static double fines = 0;
static int violation = 0;
static int answer = 1; //1 to continue or 0 to quit
static String officer = " ";
static String driver = " ";
public static void main(String[] args)
{
//input:
while (answer != 0) //while will allow the program to repeat for a new driver
{
input(officer, driver, salary, violation); //call input method
//calculations:
fines = calculateFines(violation, fines, salary, mph); //call calculateFines method
//Output:
disp(officer, driver, salary, violation,fines); //call disp method
//ask user if they would like to continue
System.out.println("Would you like to write a new ticket? Press 1 for yes or 0 for no: ");
answer = get.nextInt();
}//end while
System.out.println("Goodbye!");
}//end main
//=================================================================
public static void input(String officer, String driver, double salary, int violation) //Input Method
{
System.out.println("Officer, please enter your first and last name: ");
officer = get.nextLine();
System.out.println("Please the driver's first and last name: ");
driver = get.nextLine();
System.out.println("Please enter the driver's salary: ");
salary = get.nextDouble();
System.out.println("Press 1 if the driver ran a red light. Press 2 if the driver was speeding. Press 3 if the driver is subject to both violations. ");
violation = get.nextInt();
System.out.println("How many miles per hour was the driver going over the speed limit?: ");
mph = get.nextDouble();
}//end input
//=================================================================
public static double calculateFines(int violation, double fines, double salary, double mph) //calculates the amount of fines for either violation
{
{
if (violation == 1)
return (salary * 1.75);
else if (violation == 2)
return (salary * 1.2) + (mph * .5 * salary);
else if (violation == 3)
return (salary * 1.75) + ((salary * 1.2) + (mph * .5 * salary));
return 0;
}
}//end calculateFines
//=================================================================
public static void disp(String officer, String driver, double salary, int violation, double fines) //Display Method
{
System.out.println ("Your name is Officer " + officer + "\nThe name of the driver you pulled over is: " + driver);
System.out.println ( String.format( "The driver's annual salary is $%.2f", + salary) );
{
if (violation == 1)
System.out.println("\nThe type of traffic violation the driver received: Red Light");
else if (violation == 2)
System.out.println("\nThe type of traffic violation the driver received: Speeding");
else if (violation == 3)
System.out.println("\nThe type of traffic violation the driver received: Red Light & Speeding");
}
System.out.println ( String.format( "The amount of fines that will be assessed is $%.2f", + fines) );
}//end disp
}//end class FinFines_
Here is my issue:
When I input values for my program, the program acts as if I didn't input any names or numbers. All it says is
"Your name is Officer
The name of the driver you pulled over is:
The driver's annual salary is $0.00
The amount of fines that will be assessed is $0.00"
What can I do to make sure the program holds my inputted values?
When I press 1, to continue, it skips the first line when it asks for the officer's name. It doesn't allow me to input a name for the variable.
What can I do to make sure my program doesn't skip this line?
Is there an issue with my "return 0;" statement? If I don't include that statement then my program can't run, but I worry that me including it is making my program give 0 to all values.
I noticed that in the calculateFines() method, you have multiplied your values by 1.75. This will give 175% of the original. To find 1.75%, you need to multiply by 0.0175. This is also applicable for all other values.
Hope this helps
Though not a good practice to make everything static. Yet to just make your code work change all your methods as following -
public static void input(String officer, String driver, double salary, int violation) //Input Method {
to
public static void input() {
public static double calculateFines(int violation, double fines, double salary, double mph) //calculates the amount of fines for either violation {
to
public static double calculateFines() {
public static void disp(String officer, String driver, double salary, int violation, double fines) //Display Method {
to
public static void disp() {
This would ensure all your static fields are updated as you call these methods using the same parameters within thei definition and now your main() would include
while (answer != 0) {
input();
fines = calculateFines(); //call calculateFines method
disp();
System.out.println("Would you like to write a new ticket? Press 1 for yes or 0 for no: ");
answer = get.nextInt();
}
Note - I've cut short the text and removed comments, please do keep them in your code.
You need to read about the behavior of nextLine(), nextInt(), and nextDouble() regarding new line characters. If any of these leaves a newline character in the input buffer, then the following one will see that character and not consume any further input. This is what you are seeing.
To fix the issue, you need to read the newline character from the Scanner and ignore it. You should look at the Javadocs for Scanner to find an appropriate method to do this.
This is the same issue as #1.
Most likely there is no problem with this return as long as the if statements account for all possible values of violation. In fact, this is a very good solution because it will immediately let you see when violation has an invalid value. You should also learn about enums which allow you to define a finite number of choices for a variable.
Related
I was trying to run my code with a scanner and suddenly it errors when it goes to the 2nd question.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner stats = new Scanner(System.in);
double base,current;
float bonus;
int level;
System.out.print("Enter the base attack speed: ");
base = stats.nextDouble();
System.out.printf("Enter the bonus attack speed %: " + "%.2f");
bonus = stats.nextFloat();
System.out.println("Enter the level: ");
level = stats.nextInt();
current = (base*1+bonus*level-1) /100;
System.out.print("The character's current speed is: " + current);
}
}
% is what printf (and String.format) use for identifying a placeholder which will be filled in by a parameter provided as second argument.
You therefore have 2 bugs in this code:
The % in attack speed %: is being identified by printf as a placeholder, but you want to print an actual percent symbol. To print that, write 2 percent symbols, which is 'printf-ese' for a single percent symbol: "Enter the bonus attack speed%%: ".
You then add "%.2f" to it which is bizarre, what do you think that does? As written, if you fix the bug as per #1, you immediately get another exception because this requires an argument. The idea is that you can do something like: System.out.printf("The speed of the vehicle in km/h is: %.2f", someValue);. If someValue is, say, 39.8993, that will print the string "The speed of the vehicle in km/h is: 39.90", because you asked for: Print a value as floating point value with max 2 fractional digits. You don't have any input to print there - you're still asking the user, and you can't use this kind of thing to 'format' what the user is supposed to put in. That comes later. So presumably you want to just get rid of that entire "%.2f" thing there.
I have a compound interest calculator, but when I run the code and input the following numerals when it asks for it:
Principal: 10000
Rate: 0.02
Years:10
and choose "Annual" which is already set up so that if I or a user enters that particular string, the choice variable will automatically become 1 (or the other values already set if I enter the word Quarterly or Monthly). However, I'm supposed to be getting a value of: $12189.94 and am instead getting a value of:10200.0
Where am I doing wrong in my code?
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterest {
public static void main (String [] args)
{
Scanner cool = new Scanner (System.in);
double saving, rate;
int principal, years;
int choice;
System.out.println("Please enter you principal investment:");
/*Print statment prompts user to enter their principal investment*/
principal = cool.nextInt();
System.out.println("Would you like to have a regular investment plan?");
/* Print out statement asks user if they would like to participate in a regular investment plan*/
String question =cool.next();
System.out.println("Please enter the number of years that you wish to invest for:");
/* Print statement prompts user to enter the number of years that they wish to invest for*/
years = cool.nextInt();
System.out.println("Please enter the return rate per year:");
/* Print statement prompts user to enter the return rate per year*/
rate = cool.nextDouble();
System.out.println("What type of investment plan would you prefer (Annual, Quarterly, or Monthly)?");
String quest =cool.next();
if ("Annual".equalsIgnoreCase(quest))
{ choice =1;
}
else if ("Quarterly".equalsIgnoreCase(quest)){
choice = 4;
}
else if ("Monthly".equalsIgnoreCase(quest)){
choice = 12;
}
else {
choice = 0;
System.out.println("Please choose a investment plan or speak to a financial advisor.");
}
saving = principal*(1+(rate/choice))*Math.pow(choice,years);
System.out.println(saving);
Thank you to everyone for providing suggestions. It just seemed that I needed to use:
saving = principal * Math.pow(1+(double) (rate/ (choice)), choice * years);
In order for my equation to work as it seems my equation wasn't properly taking into consideration my integer values as saving is categorized as a double.
Your formula for calculating interest is incorrect. It should be:
saving = principal*Math.pow(1+(rate/choice), choice*years);
See the correct formula here: https://en.wikipedia.org/wiki/Compound_interest#Periodic_compounding
I am having trouble using my if and else if statements for my personal project.
My program seems to work fine in the first lines when asking the user for input, but there is a problem in the code. My compiler is asking me to use a switch method.
I've also encountered a problem where the compiler tells me I can't convert String to double, which is something I have already found using the search.
I know this might be a lot to ask but I would really appreciate your help.
/**
* This application executes number of gallons purchased, car wash if the
* customer desires.
* There will be four options, Regular, Premium, Super,
* or None. A car wash is $1.25 if purchased with $10.00 or more. If it is
* anything equal or below $9.99 then the car wash fee is $3.00.
* Regular per gallon is $2.89
* Premium per gallon is $3.09
* Super per gallon is $3.39
*
*
* #author Christian Guerra
*/
package finalflight;
//The line below is preparing the system to ask the user for inputs
import java.util.Scanner;
public class ExxonCarServices {
public static void main(String[] args) {
String gasType;
String carWash;
String gasPrice;
String numGallons;
double gasRegular = 2.89;
double gasPremium = 3.09;
double gasSuper = 3.39;
double gasNone = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Hello which type of gas would you like today? "
+ "Please make the selection Regular, Premium, Super, or None" + " ");
gasType = keyboard.nextLine();
System.out.print("How many gallons would you like?" + " ");
numGallons = keyboard.nextLine();
System.out.print("Would you like to add a professional car wash cleaning today?"
+ " " + "Please select Yes or No" + " ");
carWash = keyboard.nextLine();
if (gasType.equals("Regular")) {
gasRegular = Regular;
} else if (gasType.equals ("Premium")) {
gasPremium = Premium;
} else if (gasType.equals("Super")) {
gasSuper = Super;
} else {
gasNone = 0;
}
if (numGallons * gasPrice <10) {
carWash = 3;
} else {
carWash = 1.25;
}
}
}
The compiler is telling you that this code is correct:
if (gasType.equals("Regular")) {
gasRegular = Regular;
} ...
but starting with Java 7.0 can also be written using a switch statement:
switch (gasType) {
case "Regular":
gasRegular = Regular;
break;
case "Premium":
gasPremium = Premium;
break;
....
}
The error you're getting about "can't convert String to double" is probably due to a missing Double.parseDouble(someString) when assigning a String to a variable of the type Double.
I doubt the compiler is telling you to use a switch-case, it's probably just suggesting it (for more than a few items, a switch-case is almost always the better option for readability's sake).
To convert a String to a Double, simply use Double.parseDouble().
In your case, that would look something like this:
double numGallonsDouble = Double.parseInt(numGallons);
In my CIS 220 Java Application 2 class, we have just went over the use of objects and classes with constructors and such. The whole goal of this assignment is to utilize a class and its methods to get the user employee data. I feel I've more or less finished the whole thing, but there is one last part. The data must be validated, as explained in this screenshot link http://puu.sh/7vzeI.jpg
I would assume employee ID needs to be 9 characters long as a string. The pay rate and hours worked must be doubles. Sadly I have no idea what sort of code I need in order to validate it in the class. I figured it was a while loop but it didn't seem to work.
Here is the main java method:
public class Project3 {
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
Employee worker1 = new Employee();
worker1.getEmployeeName();
worker1.getEmployeeNum();
worker1.getPayRate();
worker1.getEmployeeHours();
System.out.println("Employee Name: " + worker1.printEmployeeName());
System.out.println("Employee ID: " + worker1.printEmployeeNum());
System.out.println("Pay Rate: $" + worker1.printPayRate());
System.out.println("Hours Worked: " + worker1.printHoursWorked());
worker1.getNetPay();
}
}
These are the methods in a class titled "Employee" which are used by main:
public String getEmployeeName()
{
System.out.println("Please enter the employee's name: ");
employeeName = console.nextLine();
return employeeName;
}
// Method that prompts the user to enter their hours worked, then returns it as the reference
public double getEmployeeHours()
{
System.out.println("Enter the number of hours worked(a numeric value between 0.0 and 100.0): ");
hoursWorked = console.nextDouble();
return hoursWorked;
}
// Method that prompts the user to enter their employee ID, then returns it as the reference
public String getEmployeeNum ()
{
System.out.println("Please enter the employee's ID: ");
employeeNum = console.nextLine();
return employeeNum;
}
// Method that prompts the user to enter their pay rate, then returns it as the reference
public double getPayRate()
{
System.out.println("Please enter the employee's pay rate (a numeric value): ");
payRate = console.nextDouble();
return payRate;
}
Please forgive me if the format of this question is hideous, as I am still quite new to stack overflow.
I think you may not be clear on the concept of return methods. There is no point in making a return method if you are not going to use the returned value at any point. For example
public String getEmployeeName()
{
System.out.println("Please enter the employee's name: ");
employeeName = console.nextLine();
return employeeName;
}
// in the other class
worker1.getEmployeeName();
You never assign the String "worker1.getEmployeeName()" to anything so making this a return statement is useless. What I would do is that I would remove the getter methods aka "worker1.printEmployeeName()" and do this instead:
String name = worker1.printEmployeeName();
System.out.println("Employee Name: " + name);
Then in the method "printEmployeeName()" I would add my checks to see if the input was valid or not. like so:
(I don't think the name could have an invalid input except for maybe if it was null, so I will use the number instead.)
Okay so to validate the information I would do this:
public String getEmployeeNum ()
{
while(true)
{
System.out.println("Please enter the employee's ID: ");
try{
employeeNum = console.nextInt(); //this should be getting an integer not the line
}catch(Exception e){
employeeNum = 0;
}
if(String.valueOf(employeeNum).length() == 9)
return String.valueOf(employeeNum); // this will break you out of your loop and return the value
else{
System.out.println("Invalid input...");
continue;
}
}
}
Now I'll try an explain the code above
Because we are using "console.nextInt();" in order to check if what the user enters is not a string, a double or anything else that is not a integer I used a try catch statement. If you are unfamiliar with how the try catch works, it basically checks if there is an error with the code in the " try{ } " part and if there is do what is in the "catch(Exception e) { } " block. I could go in to more detail on it but that explains it enough for now. So if there is a problem with the input or we find an "error" with it we set the employeeNum to "0" (You'll see why in the next part).
Then we move on to the if statement "if(String.valueOf(employeeNum).length() == 9)" basically this will turn our input into a String so we can check the length (Remember if there is an error with the input the employeeNum will be "0" with the length of "1")
If the input is valid (9 numbers long) we then return it "return employeeNum;"
If it is not valid (Not long enough or too long) we tell the user that there was an error, and we restart the process.
I hope this helps some or at least gives you an idea on what to do next!
If you want to read and learn some more:
Try Catch : http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
Edit: (A Hint)
When you check if the values are doubles for the pay rate and hours use something like this:
try {
hoursWorked = console.nextDouble();
}catch(Exception e){
hoursWorked = -1.0;
}
if(hoursWorked > 0.0)
return hoursWorked;
// the end should be the same as the other example :)
import javax.swing.JOptionPane;
public class PayCheckStatic
{
public static void main(String[] args)
{
while (name!=null)
{
String name = JOptionPane.showInputDialog("Please enter the next employees name" );
String wage = JOptionPane.showInputDialog("Please enter their hourly wage?");
String hoursWorked = JOptionPane.showInputDialog ("How many hours did they work this last work?");
double wages = Double.parseDouble(wage);
double hours = Double.parseDouble(hoursWorked);
calculatePay(name,wages,hours);
}
}
private static void calculatePay(String name,double wages,double hours)
{
if (hours > 40)
{
double pay = ((wages * 40)+((hours - 40)*(1.5 * wages)));
JOptionPane.ShowMessageDialog (null,name + "'s pay is £" + pay);
}
else
{
double pay = (wages * hours);
JOptionPane.ShowMessageDialog (null,name + "'s pay is £" + pay);
}
}
}
For some reason my code won't compile and it is coming up with cannot find symbol errors, and I can't work out why. The error is showing 3 times, with 2 of them on the message dialog boxes. Any tips as to how I can fix it?
Your main method starts with:
while(name != null)
but you have not declared name yet. You need to move the String name line before you while loop starts.
As other have pointed out, you need fix your while loop in main because of name not being defined.
However, there is also another error: your calls to JOptionPane.ShowMessageDialog() are incorrect.
The correct method you should be calling is JOptionPane.showMessageDialog() (notice the camel case method name instead of pascal case)
If the code you posted is indeed your full program, then you have an undefined name in your main() function.
You will either have to add a static variable names name in the class, so the static main() can access it or declare it locally in main(). On a second look, you do have a String name declared, but after you are trying to use it. Move the declaration of name before the if() in main()