Custom Exception output regardless of if statement - java

I'm trying to get the person's name from an input prompt. Get the name length and if the length is less than 1 throw a custom error throws LineLimitException, and prompt the user again to enter their name. I know I threw a lot of code in here but I'm hoping it makes what I'm trying to do more clearly.
LineLimitException Class
public LineLimitException(String message){
super(message);
}
}
Here I prompt and store the name field
name = input.nextLine();
int strSizeName = name.length();
if(strSizeName < 1) {
I'm getting these results in the console
How many employees are there?
2
Enter employee 1's name
Name must be greater than one character. Please try again.
Enter employee 1's name *<--- this is before I can even enter a name*
Enter employee's hourly wage *<-- prompts for hourly wage before I got the name.*
public class Driver {
/**
* defualt constructor
*/
public Driver() {
}
/**
* Main method - prompts the user for name, hours worked, and hourly salary. Stores it in a person object
* #author
* #param args
*
*/
public static void main(String[] args) throws LineLimitException{
ArrayList<Employee> person = new ArrayList<Employee>();
// prompt user for the total number of employees
Scanner input = new Scanner(System.in);
System.out.println("How many employees are there?");
String name;
int numEmployees = input.nextInt();
for (int count = 1; count <= numEmployees; count++) {
System.out.println("Enter employee " + count + "'s name");
**name = input.nextLine();
int strSizeName = name.length();
if(strSizeName < 1) {
//Why is this showing up afterI give emploee count?
System.out.println("Name must be greater than one character. Please try again.");
//reprompt the user for a name
System.out.println("Enter employee " + count + "'s name");
}else {
continue;
}**
System.out.println("Enter employee's hourly wage");
double wage = input.nextDouble();
System.out.println("Enter how many hours worked");
double hrsWkd = input.nextDouble();
person.add(new Employee(name, wage, hrsWkd)); // add an employee object to the ArrayList
printSalaryReport(person, wage, hrsWkd);
}
input.close();
System.out.println("CSV File Created.");
}
/**
* Method printSalaryReport - prints the employee person objects name, hours worked
* hourly salary and gross salary to a csv file.
* #param person in ArrayList
* #param getHours_Worked
* #param getHourly_Salary
* #throws IncorrectFileNameException
*/
private static void printSalaryReport(ArrayList<Employee> person, double getHours_Worked, double getHourly_Salary) {
String CSV_SEPARATOR = ",";
String fileName = "employee.csv";
try
{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"));
String Header = "Name, Hourly Salary, Hours Worked, Pay";
bw.write(Header.toString());
bw.newLine();
for (Employee man : person)
{
StringBuffer manStr = new StringBuffer();
manStr.append(man.getName());
manStr.append(CSV_SEPARATOR);
manStr.append(man.getHourly_Salary());
manStr.append(CSV_SEPARATOR);
manStr.append(man.getHours_Worked());
manStr.append(CSV_SEPARATOR);
manStr.append(calculateSalary(man.getHours_Worked(), man.getHourly_Salary()));
bw.write(manStr.toString());
bw.newLine();
}
bw.flush();
bw.close();
}
catch (IOException err){}
}
/**
* Method calculateSalary takes the hours worked and hourly salary and returns
* the result of each multiplied.
*
* #param getHours_Worked
* #param getHourly_Salary
* #return
*/
private static Object calculateSalary(double getHours_Worked, double getHourly_Salary) {
double salary = getHourly_Salary;
double hoursWorked = getHours_Worked;
double wkAmount = salary*hoursWorked;
return wkAmount;
}
}

boolean skip = false;
for (int count = 1; count <= numEmployees; count++) {
if (!skip)
input.nextLine();
else
skip = false;
try {
System.out.println("Enter employee " + count + "'s name");
name = input.nextLine();
int strSizeName = name.length();
if (strSizeName < 1)
throw new LineLimitException("Name must be non-empty. Please try again.");
System.out.println("Enter employee's hourly wage");
double wage = input.nextDouble();
System.out.println("Enter how many hours worked");
double hrsWkd = input.nextDouble();
person.add(new Employee(name, wage, hrsWkd)); // add an employee object to the ArrayList
printSalaryReport(person, wage, hrsWkd);
} catch (final LineLimitException e) {
System.out.println(e.getMessage());
count--;
skip = true;
}
}
Does this solve your problem?

Related

How to I do an array with a JOptionPane

The question asks "The number of fuel tanks can only be (2,4,8,10, 15,20)" this is aNbrTanks in the code below. I been trying to use an array to have these inputs. But then I get the error of Object cant be converted to int or int[] to int. I need to ask for input by JOptionPane and then ask again if it doesn't meet the standards.
package project2;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class VehicleApp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//name
String firstName = JOptionPane.showInputDialog("Please enter your first name");
while(firstName.equals("")){
firstName =JOptionPane.showInputDialog("Please enter a valid first name");
}
String lastName = JOptionPane.showInputDialog("Please enter your last name");
while(lastName.equals("")){
lastName =JOptionPane.showInputDialog("Please enter a valid first name");
}
String aName = firstName + " " + lastName;
//phone
String aphone = JOptionPane.showInputDialog("Please enter your number");
while(aphone.length()!=10){
aphone = JOptionPane.showInputDialog("Please enter a valid phone number");
}
String aPhone = ("" + aphone).replaceAll("(...)(...)(....)", "$1-$2-$3");
//vechicle number
int aNbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Vehicles"));
while(aNbrVehicles < 1 || aNbrVehicles > 10 ){
aNbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("valid number of Vehicles"));
}
//fuel tank
int aNbrTanks = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Tanks"));
VehicleFactory JarApp = new VehicleFactory(aName, aPhone, aNbrVehicles, aNbrTanks);
JarApp.calcManufacturingCost();
JarApp.calcFuelTankCost();
JarApp.calcSubtotal();
JarApp.calcTax();
JarApp.calcTotal();
JOptionPane.showMessageDialog(null, JarApp.getSummary());
}
}
I just need ideas or help figuring out how to get an array or a statement that be used as int aNbrTanks like the question asks.
You could request values in a loop, as you suggest anyway.
My example shows the loop you can use. There are more efficient ways to test for the allowed values.
int aNbrTanks = 0;
while (true) {
try {
aNbrTanks = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Tanks"));the number of Vehicles"));
} catch (NumberFormatException e) {
e.printStackTrace(e);
}
if (aNbrTanks==2) {
break;
}
}
Coming back to your title question, you can use JOptionPane with an Object[], not int[]. It will then convert your list of choices into a JComboBox. Here is an example:
public static void main(String[] args) {
Object[] choices = new Object[]{2,3,5,8};
System.out.println(Arrays.toString(choices));
Object choice = JOptionPane.showInputDialog(null, "Enter the number of Tanks", "Tanks", JOptionPane.PLAIN_MESSAGE, null, choices, 2);
System.out.println(choice);
}

Java sales program using either array or arraylist to find difference in sales made not making correct calculation

I am in a Java class and I have a sales program as a project. My code will run but will not accept a second user's name as necessary in the code. It then makes a comparison between the two salaries. But my second calculation is not working correctly. Here is what I have:
package sales2;
import java.util.Scanner;
public class Sales2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Initialise scanner
String[] empName;
empName = new String[2];
double[] annualSales;
annualSales = new double[2];
System.out.printf("Please enter the employees name:"); // Question and input
empName[0] = input.nextLine();
System.out.printf("Please enter your annual sales:");
annualSales[0] = Double.parseDouble(input.nextLine());
double salary1 = Utils2.calculateSalary(annualSales[0]); // Read sales from input & calculate salary
System.out.println(empName[0] + "'s total yearly salary is: " + Utils2.numFormat(salary1)); // Print information for user
input.nextLine();
System.out.printf("Please enter the employees name:");
empName[1] = input.nextLine();
System.out.printf("Please enter your annual sales:");
annualSales[0] = Double.parseDouble(input.nextLine());
double salary2 = Utils2.calculateSalary(annualSales[1]); // Read sales from input & calculate salary
System.out.println(empName[1] + "'s total yearly salary is: " + Utils2.numFormat(salary2)); // Print information for user
if (salary1 > salary2){
System.out.println(empName[0] + " has a higher total annual compensation.");
System.out.println(empName[1] + " will need to increase their sales to match or exceed "
+ empName[0] + ", here is how much :" + (salary1 - salary2) );
}else if (salary1 < salary2){
System.out.println(empName[1] + " has a higher total annual compensation.");
System.out.println(empName[0] + " will need to increase their sales to match or exceed "
+ empName[1] + ", here is how much :" + (salary2 - salary1) );
}else {
System.out.println("\nBoth Salespersons have equal total annual compensation.");
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sales2;
/**
*
* #author etw11
*/
import java.text.DecimalFormat;
public class Utils2 {
public final static double FIXED_SALARY = 30000;
/**
* #param dec
* #return
*/
public static String numFormat(double dec) {
return new DecimalFormat("##,##0.00").format(dec);
}
/**
* Calculates the salary based on the given sales.
* #param sales The annual sales
* #return The calculated salary.
*/
public static double calculateSalary(double sales) {
double commissionRate = 0.10d;
if (sales < 320000) {
commissionRate = 0.00d;
} else if (sales >= 320000 && sales < 400000) {
commissionRate = 0.08d;
}
// System.out.println("The current commission is " + (int)
(commissionRate * 100) + "% of total sales.");
return FIXED_SALARY + (sales * commissionRate);
}
}
change this:
double annualSales = input.nextDouble();
to this:
double annualSales = Double.parseDouble(input.nextLine());
Found my issue. In this line:
annualSales[0] = Double.parseDouble(input.nextLine());
It should be:
annualSales[1] = Double.parseDouble(input.nextLine());

Java - object can't store data

My dad and I narrowed it down to the object can't store the data. also, I'm new to java. The code is supposed to print in the console the first name, last name, grade, and grade average. I think the problem is in public double getCalcGraeAverage() but correct me if wrong, please.
import java.util.Scanner;
/**
* Write a description of class Student here.
*
* #author XXXX
* #version XXXX
*/
public class Student
{
String firstName;
String lastName;
int gradeLevel;
double gradeAverage;
int totalAssignments;
double totalPoints;
/**
* Create a new student with student's name, grade, and average
*/
public Student(String newFirstName, String newLastName, int newGradeLevel, double newGradeAverage)
{
firstName = newFirstName;
lastName = newLastName;
gradeLevel = newGradeLevel;
gradeAverage = newGradeAverage = 0.0;
}
/**
* Return the student's first name.
*/
public String getFirstName()
{
return firstName;
}
/**
* Return the student's last name.
*/
public String getLastName()
{
return lastName;
}
/**
* Return the grade level of the student.
*/
public int getGradeLevel()
{
return gradeLevel;
}
/**
* Calculates grade average.
*/
public double getCalcGradeAverage()
{
double gradeAverage = totalAssignments / totalPoints;
return gradeAverage;
}
public static void main (String[] args)
{
Student student1 = new Student ("XXXX", "XXXX", 11, 0.0);
System.out.println("The student's first name is: " + student1.getFirstName());
System.out.println("The student's last name is: " + student1.getLastName());
System.out.println("The student's grade level is: " + student1.getGradeLevel());
System.out.println("Please enter the total assignment points the student has earned: ");
Scanner input = new Scanner(System.in);
Double totalAssignments = input.nextDouble();
System.out.println("Please enter the number of assignments given: ");
double totalpoints = input.nextDouble();
System.out.println(student1.getFirstName() + " " + student1.getLastName() + " average grade is" + student1.getCalcGradeAverage());
}
}
In your code you are :
creating a Student student1 object
reading totalAssignments, totalpoints from System.in
calling student1.getCalcGradeAverage()
between steps 2 and 3 you have to set the fields totalAssignments, totalpoints of student to the values you read or they will retain their default values of zero. E.g.
student1.totalAssignments = totalAssignments;
student1.totalpoints = totalpoints;
Also, since totalAssignments is of type int, you probably want to read it as:
int totalAssignments = input.nextInt();
When writing your code, you declare variables for the student class with class scope.
int totalAssignments;
double totalPoints;
those class scope variable are used in the method :getCalcGradeAverage()
totalAssignments of Student and totalPoints of student are used in this method
When you create a new Student those variable are equals to zero because not affected by a value in your constructor.
in the main method when you writes :
Double totalAssignments =
you declare a new variable named "totalAssignments" with a method scope.When the method ends, the variable reference goes away and there is no way to access that variable any longer.
you can consider that the variable decalred is not the same that the student variable: student.totalAssignments is always equals to zero because no value affected to him.
Then assuming that you can do that :
student1.totalAssignments = input.nextInt();
student1.totalPoints = input.nextDouble();

Making an array of SIZE = 10 employee objects [duplicate]

This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 7 years ago.
Is there anyone who could guide me in the right direction on how to create an array of these employees? The array is set to a constant SIZE=10; Here is the my employee class and the driver with the array I tried. Also, I am aware that most of the output will be blank (employee name, id, etc) As I already know how to write it but so far have not. Also the "1" in class name "Employee 1" is only there because I already had another file saved under employee. Very new to java as you can most likely tell. Thank you
class Employee1{
//variables
private String name;
private double grossPay;
// This is the constructor of the class Employee
public Employee1(String EmpName)
{
name = EmpName;
}
//calculates gross pay and returns
public double weeklyPay(double hoursWorked, double hourlyRate)
{
double timeAndHalf = (hourlyRate/2.0)+hourlyRate;
double dblOvtHours;
double dblOvtPay;
double regHours;
double ovtHours;
if (hoursWorked <= 40)
{
grossPay = hoursWorked*hourlyRate;
}
else if (hoursWorked > 40 && hoursWorked <= 60)
{
ovtHours = hoursWorked-40;
regHours = 40;
grossPay = (ovtHours*timeAndHalf) + (regHours*hourlyRate);
}
else if (hoursWorked > 60)
{
ovtHours = 20;
regHours = 40;
dblOvtHours = hoursWorked - 60;
dblOvtPay = hourlyRate * 2;
grossPay = (dblOvtPay*dblOvtHours) + (timeAndHalf * ovtHours)
+(regHours * hourlyRate);
}
return grossPay;
}/////////////////////////////////////////////////
/* Print the Employee details */
public String toString()
{
return "Employee Report\n" + "Name :" + "\nID number :"
+ "\nHours Worked" + "\nHourly Rate : " +"\nGross pay: " + grossPay ;
}
}
my driver class:
import java.util.Scanner;
public class EmployeeDriver{
public static void main(String args[]){
// Invoking methods for each object created
final double hourlyRatef = 10.25;
double hoursWorkedf, wPay;
double grossPayf = 0.0;
Scanner input = new Scanner(System.in);
System.out.print("Please enter the number of hours work: ");
hoursWorkedf = input.nextDouble();
//array that does not work //
Employee1 emp = new Employee1();
emp[0] = new Employee ();
/* invoke weeklyPay() method */
grossPayf= emp.weeklyPay(hoursWorkedf,hourlyRatef);
// invoke printEmployee() method
System.out.println (emp.toString());
}
}
What you are doing is creating a single object, not an array. An array would look like this:
final int SIZE = 10;
Employee1[] emp = new Employee1[SIZE];
Then each member of the array would have to be instantiated like this:
emp[0] = new Employee1();
public static final int SIZE = 10;
public static void main(String[] args) {
Employee1[] employees = new Employee1[SIZE];
}
As per Java doc:
An array is a container object that holds a fixed number of values of a single type.
In your case you are instantiating an object (Employee1 emp) and setting it at index 0. What about other indexes? You nee to run a loop and ask user for new employee and insert it at proper index ( 0-> 1 ->2 and so on).
Also your constructor accepts name of employee which you should also provide and print it in toString method. I have made some changes and the final code looks like:
public class Employee1 {
//variables
private String name;
private double grossPay;
// This is the constructor of the class Employee
public Employee1(String EmpName)
{
name = EmpName;
}
//calculates gross pay and returns
public double weeklyPay(double hoursWorked, double hourlyRate)
{
double timeAndHalf = (hourlyRate/2.0)+hourlyRate;
double dblOvtHours;
double dblOvtPay;
double regHours;
double ovtHours;
if (hoursWorked <= 40)
{
grossPay = hoursWorked*hourlyRate;
}
else if (hoursWorked > 40 && hoursWorked <= 60)
{
ovtHours = hoursWorked-40;
regHours = 40;
grossPay = (ovtHours*timeAndHalf) + (regHours*hourlyRate);
}
else if (hoursWorked > 60)
{
ovtHours = 20;
regHours = 40;
dblOvtHours = hoursWorked - 60;
dblOvtPay = hourlyRate * 2;
grossPay = (dblOvtPay*dblOvtHours) + (timeAndHalf * ovtHours)
+(regHours * hourlyRate);
}
return grossPay;
}/////////////////////////////////////////////////
/* Print the Employee details */
public String toString()
{
return "Employee Report\n" + "Name :" + name + "\nID number :"
+ "\nHours Worked" + "\nHourly Rate : " +"\nGross pay: " + grossPay ;
}
}
And the main is:
public static void main(String[] args) {
final double hourlyRatef = 10.25;
double hoursWorkedf, wPay;
double grossPayf = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("How many employees you want to enter: ");
final int empSize = input.nextInt();
Employee1[] employees = new Employee1[empSize];
for (int i = 0; i <empSize; i++) {
System.out.print("Please enter the number of hours work: ");
hoursWorkedf = input.nextDouble();
employees[0] = new Employee1("John");
grossPayf = employees[0].weeklyPay(hoursWorkedf,hourlyRatef);
System.out.println (employees[0].toString());
}
}
Note: I have done only minimum changes to make the program work. There are various other things you can improve in your code. The program runs as:
How many employees you want to enter:
2
Please enter the number of hours work: 11
Employee Report
Name :John
ID number :
Hours Worked
Hourly Rate :
Gross pay: 112.75
Please enter the number of hours work: 10
Employee Report
Name :John
ID number :
Hours Worked
Hourly Rate :
Gross pay: 102.5
new code
public static void main(String[] args) {
final int SIZE=10;
final double hourlyRatef = 10.25;
double hoursWorkedf, wPay;
double grossPayf = 0.0;
String name = "Void";
Scanner input = new Scanner(System.in);
// System.out.println("How many employees you want to enter: ");
// final int empSize = input.nextInt();
Employee1[] employees = new Employee1[SIZE];
for (int i = 0; i <SIZE; i++)
{
System.out.print("Please enter the number of hours work: ");
hoursWorkedf = input.nextDouble();
System.out.print("Please enter employee name: ");
employees[i] = new Employee1(name);
grossPayf = employees[i].weeklyPay(hoursWorkedf,hourlyRatef);
System.out.println (employees[i].toString());

Why does this array go out of bounds inconsistently?

This is a Student class I have which creates a student that has a name, grade, and ID number. The Student is used as the key in a TreeMap, while the student's grade is used as the value. I wrote compareTo as I am implementing Comparable, but this error pops up upon entering in the first student:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Student.<init>(Student.java:25)
at Main.main(Main.java:50)
Java Result: 1
I think it is coming from the splitting of the student's name into a String[], but I've tested those lines that call the first and last names, as well as the line that splits the name and they all seem to work as intended, except for when they are called in compareTo.
Any help would be much appreciated.
public class Student implements Comparable<Student>{
private String name, grade, first, last;
private String[] stuName;
private int id;
/**
* Constructs a new Student with a name, ID Number, and a grade.
* #param n name
* #param i ID Number
* #param g grade
*/
public Student(String n, int i, String g){
name = n;
id = i;
grade = g;
stuName = n.split(" ");
first = stuName[0];
last = stuName[1];
}
/**
* Compares Students. First by last name, then by first if the last names
* are the same. If the first names are also the same, the students are
* compared by their ID Numbers.
* #return the value upon comparing the proper property of the Student
*/
#Override
public int compareTo(Student other){
if (last.equals(other.getLast())){
if (first.equals(other.getFirst())){
return id - other.getID();
}else
return first.compareTo(other.getFirst());
}
return last.compareTo(other.getLast());
}
/**
* Changes the student's current grade.
* #param g new grade
*/
public void changeGrade(String g){
grade = g;
}
/**
* Returns student's name.
* #return name
*/
public String getName(){
return name;
}
/**
* Returns student's first name.
* #return first name
*/
public String getFirst(){
return first;
}
/**
* Returns student's last name.
* #return last name
*/
public String getLast(){
return last;
}
/**
* Returns the student's grade.
* #return grade
*/
public String getGrade(){
return grade;
}
/**
* Returns the student's ID Number
* #return id number
*/
public int getID(){
return id;
}
Tester:
public class Main {
public static void main(String[] args) throws InterruptedException{
Map<Student, String> students = new TreeMap();
Scanner in = new Scanner(System.in);
System.out.println("How many students do you want to add?");
int numStudents = in.nextInt();
String name, grade;
int id;
for (int i = 1; i < numStudents; i++){
System.out.println("Name of student " + i + "?");
name = in.nextLine();
in.nextLine();
System.out.println("Grade of " + i + "?");
grade = in.nextLine();
System.out.println("ID Number of " + i + "?");
id = in.nextInt();
Student s = new Student(name, id, grade);
students.put(s, s.getGrade());
}
System.out.println("How many students do want to remove");
int remStudents = in.nextInt();
for (int i = 0; i < remStudents; i++){
System.out.println("ID?");
int remID = in.nextInt();
for (Student s : students.keySet()){
if (s.getID() == remID){
students.remove(s);
}
}
}
System.out.println("How many grades do you want to change?");
int changeGrades = in.nextInt();
for (int i = 0; i < changeGrades; i++){
System.out.println("ID?");
int foo = in.nextInt();
System.out.println("New grade?");
String newGrade = in.nextLine();
for (Student s : students.keySet()){
if (s.getID() == foo){
s.changeGrade(newGrade);
}
}
}
String printout = "";
for (Student s : students.keySet()){
printout += s.getLast() + ", " + s.getFirst() + " (" + s.getID() + "): " + s.getGrade() + "\n";
}
System.out.println(printout);
}
}
Probably because you have two different loops, with different indices:
in your one loop, you start from 1, and thus you are 1 student short:
for (int i = 1; i < numStudents; i++){
in the delete loop you have a 0-based index:
for (int i = 0; i < remStudents; i++){
I suspect that, you think you add 2 studends, but really you have just one (at index 0), and thus your indexout-of-bounds exception.
EDIT, OP has added a 'full' stack for the exception, and the above answer is not related to the OP's problem.....
Answer 2: Based on your revised stack/exception edit, the only possible answer is that there are no spaces in the student's name..... your assertion that there is always a space is simply not true ....
you may want to add a count qualifiewr to the split so that you will get an empty string on any invalid input:
stuName = n.split(" ", 2);

Categories