so I have exercise from a college to finish and I believe I am close to it but yet so far. I am not asking for a specific answer, I would love to know how to "overwrite a variable?" (not sure if thats a right name for that kind of action).
Here is the question : http://pastebin.com/riDYS39D
The problem which I have is that, I don't know exactly how to overwrite data in variable which was created in if statement.
and the code, any help is always welcome
import java.util.Scanner;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double grossPaid, allowance1, allowance2, totalTaxPaid, netPay, grossAfterAllowance;
double taxSaved;
final double GROSSRATIO;
String idNumber, name, address, strln;
char maritalStatus;
allowance1 = 25000;
allowance2 = 20000;
GROSSRATIO = 500000;
taxSaved = 0.00;
/* trash
grossAfterAllowance = grossPaid - allowanceGiven;
totalTaxPaid = grossAfterAllowance - netPay;
*/
System.out.println("Enter your employee identification number: ");
idNumber = input.nextLine();
System.out.println("Enter your name: ");
name = input.nextLine();
System.out.println("Enter your address: ");
address = input.nextLine();
System.out.println("Enter your marital status: ");
strln = input.next();
maritalStatus = strln.charAt(0);
if (maritalStatus == 'S')
taxSaved = 0.20;
if (maritalStatus == 'M')
taxSaved = 0.23;
System.out.println("Enter your gross payment: ");
grossPaid = input.nextDouble();
if (grossPaid < GROSSRATIO)
netPay = (grossPaid - allowance1) * taxSaved;
if (grossPaid >= GROSSRATIO)
netPay = (grossPaid - allowance2) * taxSaved;
System.out.println(maritalStatus);
netPay = (grossPaid * maritalStatus);
System.out.println("Name: " + name);
System.out.println("ID: " + idNumber);
System.out.println("Address: " + address);
System.out.println("Marital Status: " + strln);
System.out.println("Gross Payment: " + grossPaid);
System.out.println("Net pay: " + netPay);
}
}
Considering your first input variable idNumber, this is how you overwrite a variable:
String idNumber = "";
System.out.println("Enter your employee identification number: ");
idNumber = input.nextLine();
System.out.println("ID Number: " + idNumber);
System.out.println("Enter your updated employee identification number: ");
idNumber = input.nextLine();
System.out.println("Updated ID Number: " + idNumber);
You said "any help is always welcome" so here is my analysis of your code.
It is general practice to declare your variables as close to their usage as possible, most often that means when first assigned, e.g.:
String address = input.nextLine();
Marital status is supposed to be lowercase 's' or 'm'. You should use nextLine() and validate it, e.g.
char maritalStatus;
do {
System.out.println("Enter your marital status (s/m):");
String line = input.nextLine();
maritalStatus = (line.length() == 1 ? line.charAt(0) : '?');
} while (maritalStatus != 's' && maritalStatus != 'm');
Your GROSSRATIO is supposed to be 50000, not 500000.
You are inconsistent about use of constants.
GROSSRATIO is uppercase and final. Perfect!
allowance1 and allowance2 are lowercase and not final.
0.20 and 0.23 are not named constants.
maritalStatus is a char, so this line compiles, but is definitely not what you want, and is the cause of your "strange outputs". Just remove the line:
netPay = (grossPaid * maritalStatus);
You are also printing maritalStatus by itself without label. Remove it.
You have two if statements for assigning netPay that are opposites, but compiler doesn't see that, so netPay is not definitely assigned. Just change second if statement to else.
totalTaxPaid and grossAfterAllowance are not used. Remove them.
The calculation of netPay actually calculates totalTax.
You are not printing all required output.
Related
The bottom section is where it is stuffing up. When The if statements start after while, the product doesn't store the name of the product (but keeps what product it is and the cost for later - so the end result works).
The issue is, regardless of what is entered, the message still comes up "That isn't a valid product" even if it is. It doesn't affect the program, but does affect the output.
import java.util. * ;
public class Shopping {
String p1Name,
p2Name,
p3Name; // variables for storing product names
double p1UP,
p2UP,
p3UP; // variables for storing product unit prices
String c1Name,
c2Name; // variables for storing customer names
double c1DRate,
c2DRate; // variables for customer discount rates
double quant; //variables for unit quantity required
double sum; // unit and quantity
String custName; // Customer name
double discount1;
double discount2;
String product;
double cost = p1UP;
Scanner scan;
public void setProductData() {
System.out.println("Initializing product data");
System.out.print("Enter name of part 1 : ");
p1Name = scan.next();
System.out.print("Enter unit price of part 1 : ");
p1UP = scan.nextDouble();
System.out.print("Enter name of part 2 : ");
p2Name = scan.next();
System.out.print("Enter unit price of part 2 : ");
p2UP = scan.nextDouble();
System.out.print("Enter name of part 3 : ");
p3Name = scan.next();
System.out.print("Enter unit price of part : ");
p3UP = scan.nextDouble();
}
public void setCustomerData() {
System.out.println("Initializing customer data");
System.out.print("Enter name of customer 1 : ");
c1Name = scan.next();
System.out.print("Enter discount Rate for customer 1 : ");
c1DRate = scan.nextDouble();
System.out.print("Enter name of customer 2 : ");
c2Name = scan.next();
System.out.print("Enter discount Rate for customer 2 : ");
c2DRate = scan.nextDouble();
}
public void computeCost() {
// prompt and read product name, qty and customer name before computing and
// printing the cost taking into consideration customer specific discounts.
boolean discount1 = false;
boolean discount2 = false;
System.out.print("Please enter your name : ");
custName = scan.next();
if (custName.equalsIgnoreCase(c1Name)) {
discount1 = true;
}
if (custName.equalsIgnoreCase(c2Name)) {
discount2 = true;
}
// Determined if customer eligible for a discount
System.out.println("Our products and prices are as follows");
System.out.println(p1Name + " is priced at " + p1UP);
System.out.println(p2Name + " is priced at " + p2UP);
System.out.println(p3Name + " is priced at " + p3UP);
System.out.println("What product would you like");
//what product did they want to buy
product = scan.next();
while (! (product.equalsIgnoreCase(p1Name) || product.equalsIgnoreCase(p2Name) || product.equalsIgnoreCase(p3Name))) {
System.out.println("That isn't a valid product.");
product = scan.next();
}
if (product.equals(p1Name)) {
cost = p1UP;
}
if (product.equals(p2Name)) {
cost = p2UP;
}
if (product.equals(p3Name)) {
cost = p3UP;
}
else {
System.out.println("You have selected an incorrect product");
System.out.println("You have been assigned " + p1Name + " instead");
}
scan.nextLine();
I think you're having a mistake here.
I suppose you're trying to print the message "That isn't a valid product." if the input does not match any of p1Name, p2Name and p3Name, right?
So your while condition must be NOT EQUALS to p1Name AND p2Name, p3Name too.
So you can use this:
while (!(product.equalsIgnoreCase(p1Name) && !(product.equalsIgnoreCase(p2Name)) && !
(product.equalsIgnoreCase(p3Name)))) {
System.out.println("That isn't a valid product.");
product = scan.next();
}
use String.trim() maybe when you scan you scan also the space or whitespace character.
in ur while condition :
!(product.trim().equalsIgnoreCase(p1Name.trim()) || product.trim().equalsIgnoreCase(p2Name.trim()) || product.trim().equalsIgnoreCase(p3Name.trim()))
Ok, I worked it out.
I had if
not else if for the later statements.
my bad.
Thanks
My first assignment is to develop a code that allows the user to input data for the distance in miles they wish to travel, the fuel efficiency, and the cost of gas. Then create a code in order to calculate the total cost of the trip.
I have all the code for all the input values but I'm having trouble with the equation itself. Java is not recognizing "/". I can't understand what I'm doing unless I need to add a bit more code for the equation to work.
import java.util.Scanner;
public class DrivingCost
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Please enter your distance (miles): ");
Scanner t = new Scanner(System.in);
System.out.print("Please enter vehicle's fuel efficiency (mpg): ");
Scanner u = new Scanner(System.in);
System.out.print("Please enter the price per gallon (dollars): ");
String distanceInMiles = s.nextLine();
System.out.println("The distance (miles): " + distanceInMiles);
String fuelEfficiency = t.nextLine();
System.out.println("Fuel efficiency (mpg):" + fuelEfficiency);
String pricePerGallon = u.nextLine();
System.out.println("Price per gallon (dollars): " + pricePerGallon);
double tripCost = (distanceInMiles / fuelEfficiency) * pricePerGallon;
System.out.println("The trip cost (dollars): " + tripCost);
}
}
This is the error I keep recieving:
DrivingCost.java:32: error: bad operand types for binary operator '/'
double tripCost = (distanceInMiles / fuelEfficiency) * pricePerGallon;
^
You're doing Math operation on String, you can't, you need double type
Double.parseDouble(sc.nextLine()); reads a line and parse to a double (benefits : avoid return line error in general, good habit to have)
sc.nextDouble() reads directly for a double
Use only one Scanner per source
Have a good order between print and scanner asking
Scanner sc = new Scanner(System.in);
System.out.print("Please enter your distance (miles): ");
String distanceInMiles = Double.parseDouble(sc.nextLine());
System.out.println("The distance (miles): " + distanceInMiles);
System.out.print("Please enter vehicle's fuel efficiency (mpg): ");
String fuelEfficiency = Double.parseDouble(sc.nextLine());
System.out.println("Fuel efficiency (mpg):" + fuelEfficiency);
System.out.print("Please enter the price per gallon (dollars): ");
String pricePerGallon = Double.parseDouble(sc.nextLine());
System.out.println("Price per gallon (dollars): " + pricePerGallon);
double tripCost = (distanceInMiles / fuelEfficiency) * pricePerGallon;
System.out.println("The trip cost (dollars): " + tripCost);
You are trying to do calculations with strings. You have to parse doubles out of your string inputs. Just change your equation line to this:
double tripCost = (Double.valueOf(distanceInMiles) / Double.valueOf(fuelEfficiency)) * Double.valueOf(pricePerGallon);
P.S. Proper input validation would be a good improvement. In case user provide incorrect input. Also, as mentioned in the comments there is no need to use multiple Scanners. One will be enough.
You can get distanceInMiles, fuelEfficiency and pricePerGallon in double using s.nextDouble().
After that you should be able to perform double operation on these variables.
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Please enter your distance (miles): ");
double distanceInMiles = s.nextDouble();
System.out.println("The distance (miles): " + distanceInMiles);
System.out.print("Please enter vehicle's fuel efficiency (mpg): ");
double fuelEfficiency = s.nextDouble();
System.out.println("Fuel efficiency (mpg):" + fuelEfficiency);
System.out.print("Please enter the price per gallon (dollars): ");
double pricePerGallon = s.nextDouble();
System.out.println("Price per gallon (dollars): " + pricePerGallon);
double tripCost = (distanceInMiles / fuelEfficiency) * pricePerGallon;
System.out.println("The trip cost (dollars): " + tripCost);
}
I am relatively fresh (couple weeks) into Java and I am messing around with an Employee input system with ArrayLists. Anyway I want to ensure no matter the user input that that name in the output is the same format.
Example:
Input --> Enter Employee Name: SAMANTHA
Output --> Employee Name: Samantha
Here is the code I am running, I am just not sure where within this I could set that formatting.
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeTester_v5
{
public static void main (String[] args)
{
//ASSIGN VARIABLES
String c = "";
String newEmployee = "";
double yearToDate = 0.0;
double increase = 0.025;
double newSalary = 0.0;
//ARRAY LISTS
ArrayList<String>first = new ArrayList<String>();
ArrayList<String>last = new ArrayList<String>();
ArrayList<Double>salary = new ArrayList<Double>();
ArrayList<Integer>months = new ArrayList<Integer>();
//SCANNER INPUT
//create a new scanner
Scanner input = new Scanner(System.in);
//WHILE LOOP - to keep asking for user input until "No" is entered
do{
//USER INPUT
System.out.println ("Enter employee first name: ");
first.add(input.next());
System.out.println ("Enter employee last name: ");
last.add(input.next());
System.out.println ("Enter employee salary: ");
salary.add(input.nextDouble());
System.out.println ("Number of months worked this year: ");
months.add(input.nextInt());
System.out.println("Enter another employee in the system?");
c = input.next();
}while(c.equalsIgnoreCase("Yes"));
System.out.println();
//ARRAY OUTPUT
for(int i=0; i < first.size(); i++)
{
yearToDate = months.get(i) * salary.get(i)/12;
newSalary = (increase * salary.get(i)) + salary.get(i);
System.out.print("Employee Name: " + first.get(i) + " ");
System.out.print(last.get(i)+"\n");
System.out.printf("Current Salary: $%.2f\n", salary.get(i));
System.out.printf("Year to Date: $%.2f\n", yearToDate);
System.out.printf("New Salary: $%.2f\n", newSalary);
System.out.println("----------------------");
}
}
}
First thing you should do is to check out String API https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
It's a must-know when it comes to Java, you'll need it in possibly every project you'll work on :)
There are plenty of ways to achieve your goal here.
What you could do for example is to capitalize the first letter and then append the rest of the String that you'll force to lowercase - check out the snippet below.
String inputString = input.next();
String resultString = inputString.substring(0, 1).toUpperCase() + inputString.substring(1).toLowerCase();
Try like this :
System.out.print("Employee Name: " + first.get(i).substring(0,1).toUpperCase()+first.get(i).substring(1).toLowerCase() + " ");
this one first.get(i).substring(0,1).toUpperCase() gest your first letter in string upper, and first.get(i).substring(1).toLowerCase() gets letters from index 1 - so from the 2nd letter of the string to lower.
Maybe what the OP is not understanding, is that this can be wrapped in a private method, like this:
private String fixCapitalisation(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
}
Then your line uses this by adjusting the line that prints the name:
System.out.print("Employee Name: " + fixCapitalisation(first.get(i)) + " ");
You can then reuse this function on the last name too...
Here is the entire class with this change:
package Dunno;
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeTester_v5
{
public static void main (String[] args)
{
//ASSIGN VARIABLES
String c = "";
String newEmployee = "";
double yearToDate = 0.0;
double increase = 0.025;
double newSalary = 0.0;
//ARRAY LISTS
ArrayList<String>first = new ArrayList<String>();
ArrayList<String>last = new ArrayList<String>();
ArrayList<Double>salary = new ArrayList<Double>();
ArrayList<Integer>months = new ArrayList<Integer>();
//SCANNER INPUT
//create a new scanner
Scanner input = new Scanner(System.in);
//WHILE LOOP - to keep asking for user input until "No" is entered
do{
//USER INPUT
System.out.println ("Enter employee first name: ");
first.add(input.next());
System.out.println ("Enter employee last name: ");
last.add(input.next());
System.out.println ("Enter employee salary: ");
salary.add(input.nextDouble());
System.out.println ("Number of months worked this year: ");
months.add(input.nextInt());
System.out.println("Enter another employee in the system?");
c = input.next();
}while(c.equalsIgnoreCase("Yes"));
System.out.println();
//ARRAY OUTPUT
for(int i=0; i < first.size(); i++)
{
yearToDate = months.get(i) * salary.get(i)/12;
newSalary = (increase * salary.get(i)) + salary.get(i);
System.out.print("Employee Name: " + fixCapitalisation(first.get(i)) + " ");
System.out.print(last.get(i)+"\n");
System.out.printf("Current Salary: $%.2f\n", salary.get(i));
System.out.printf("Year to Date: $%.2f\n", yearToDate);
System.out.printf("New Salary: $%.2f\n", newSalary);
System.out.println("----------------------");
}
}
//New Method to fix capitalisation
private static String fixCapitalisation(String input) {
return input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase();
}
I hope my answer might help you to understand the answers already given better, and how the duplicate answer i provided is relevant - the use of an ArrayList here makes no difference to the String manipulation.
You should consider defining your own class of "Employee", that can persist the name, salary etc. then you only need one ArrayList, you currently have lists with values that are Logically linked by their position in the Array, but there is no technical dependency on that.
New here (and to Java!). I've searched around the site for an answer to my problem but came up naught. This program executes up to the scan.nextDouble statement.
If I enter a salary value such as "8," I get:
/////OUTPUT/////
Enter the performance rating (Excellent, Good, or Poor):
Current Salary: $8.00
Amount of your raise: $0.00
Your new salary: $8.00
/////END OF OUTPUT/////
So obviously, my following scan.nextLine and all the if-else statements are bypassed. What am I missing?
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary
{
public static void main(String[] args)
{
double currentSalary; // employee's current salary
double raise = 0; // amount of the raise
double newSalary = 0; // new salary for the employee
String rating; // performance rating
String rating1 = new String("Excellent");
String rating2 = new String("Good");
String rating3 = new String("Poor");
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.nextLine();
// Compute the raise using if ...
if (rating.equals(rating1))
raise = .06;
else
if (rating.equals(rating2))
raise = .04;
else
if (rating.equals(rating3))
raise = .015;
else
newSalary = currentSalary + currentSalary * raise;
// Print the results
{
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
}
When you scan input using scanner.nextDouble() it takes only the float value and leaves the new line character in the buffer so after that when you do scanner.nextLine(() it takes the new line character and returns empty string.Put another scanner.nextLine() before scanning the next line to eat up the new line character
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
scan.nextLine();
rating = scan.nextLine();
Scanner.nextDouble() just reads the next available double value and does not by itself point to next line.
use a dummy scanner.nextLine() before your actual one. that lets your cursor point to next line from which your scanner.nextline() takes the input.
-cheers :)
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 ---");
}
}
}
}