JAVA Employee Type with Arrays - java

package javaapplication2;
import java.util.Scanner;
public class JavaApplication2
{
public static void main(String[] args)
{
person_type salespeople[] = new person_type [100];
person_type person = new person_type();
int counter = 0;
person.gross=0;
person.salary=0;
System.out.println("How many workers are there?");
Scanner number_of_workers = new Scanner(System.in);
counter=number_of_workers.nextInt();
for(int i=0; i<counter; i++)
{
salespeople[i] = person;
System.out.println(person.salary);
}
for(int i=0; i<counter; i++)
{
System.out.print("Enter the salary of the salesperson ");
System.out.print(i+1);
System.out.println(":");
Scanner salary = new Scanner(System.in);
salespeople[i].salary = salary.nextInt();
System.out.print("Enter the gross of the salesperson ");
System.out.print(i+1);
System.out.println(":");
Scanner gross = new Scanner(System.in);
salespeople[i].gross = gross.nextInt();
System.out.println("1---- " + salespeople[0].salary);
System.out.println(i);
}
System.out.println("First worker's salary is: " + salespeople[0].salary);
System.out.println("First worker's gross " + salespeople[0].gross);
System.out.println("Second worker's salary is: " + salespeople[1].salary);
System.out.println("Second worker's gross is: " + salespeople[1].gross);
}
private static class person_type
{
int salary;
int gross;
}
}
I am trying to put every employee stored to the array, but all the employees' details are overwritten by the very last one entered by the user. Can you please help? Thanks in advance!!

All the elements in the array refer to the same person_type instance :
for(int i=0; i<counter; i++)
{
salespeople[i] = person;
System.out.println(person.salary);
}
You must create a new person_type instance for each index of the array.
for(int i=0; i<counter; i++)
{
salespeople[i] = new person_type ();
}
BTW, I suggest you change your class name to either Person or PersonType to conform to Java naming conventions.

Related

Why isn't my JOptionPane.showMessageDialog working?

I'm a beginner programmer and I wrote this for my school class. But somehow even my JOptionPane.showMessageDialog under displaypay() won't work!!! I expect that a message box will pop up, but instead after I enter the amount of hours for each day, nothing happens! It doesn't even skip the part, the whole program just pauses! I am so confused! Instead if I use System.out.println(), it works fine.
Also I don't want to do System.out.println for the displaypay(), I have to use showMessageDialog.
package payroll.program;
import java.util.Scanner;
import javax.swing.JOptionPane; //imports
class Employee
{
int hourlypay;
int totalhours = 0;
String name; //variables
void getname()
{
Scanner scan = new Scanner(System.in);
System.out.println("What is this employee's name?");
name = scan.next(); //gets name
}
void calculatepay()
{
int[] hours = new int[5]; //creates array for hours
Scanner scan = new Scanner(System.in);
System.out.println("How much is " + name + " paid per hour?");
hourlypay = scan.nextInt(); //gets hourly pay
for (int i = 0; i < 5; i++)
{
System.out.println("How many hours did " + name + " work on day " + (i + 1) + "?");
hours[i] = scan.nextInt(); //gets hour on each day
totalhours = totalhours + hours[i]; //adds hours up
}
}
void displaypay()
{
JOptionPane.showMessageDialog(null, "You have to pay " + " $" + totalhours * hourlypay + " to " + name + "!"); //displays total pay
}
}
public class PayrollProgram {
public static void main(String[] args) {
int numberofemployees; //variable for # of employees
System.out.println("Welcome to the Payroll Program!"); //welcomes user
Scanner scan = new Scanner(System.in);
System.out.println("How many employees do you have?");
numberofemployees = scan.nextInt(); //gets input for # of employees
Employee[] ArrayofEmployees = new Employee[numberofemployees]; //creates array of employees with the same size as the number of employees
for (int i = 0; i < numberofemployees; i++)
{
ArrayofEmployees[i] = new Employee(); //creates an Employee for each space in the array
}
for (int i = 0; i < numberofemployees; i++)
{
ArrayofEmployees[i].getname();
ArrayofEmployees[i].calculatepay();
ArrayofEmployees[i].displaypay(); //runs functions in class Employee for each employee
}
}
}
This is my program and the JOptionPane.showMessageDialog doesn't work.
Please help!
When you try to display swing components, you are expected to do so from an event dispatching thread. Otherwise, you won't get reliable results. So, in this case, wrap all your code inside your main inside a call to SwingUtilities.invokeLater:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
int numberofemployees; //variable for # of employees
System.out.println("Welcome to the Payroll Program!"); //welcomes user
Scanner scan = new Scanner(System.in);
System.out.println("How many employees do you have?");
numberofemployees = scan.nextInt(); //gets input for # of employees
Employee[] ArrayofEmployees = new Employee[numberofemployees]; //creates array of employees with the same size as the number of employees
for (int i = 0; i < numberofemployees; i++) {
ArrayofEmployees[i] = new Employee(); //creates an Employee for each space in the array
}
for (int i = 0; i < numberofemployees; i++) {
ArrayofEmployees[i].getname();
ArrayofEmployees[i].calculatepay();
ArrayofEmployees[i].displaypay(); //runs functions in class Employee for each employee
}
}
});
}
More info can be found here: The Event Dispatch Thread.
In particular, notice what it says can happen if you fail to run Swing components from the event dispatcher thread:
Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.

How to fix my Array class

I am trying to figure out how to get my array to run correctly, I know I have to change the array value to an input but I cannot get the program to compile if any one can help that be great.
I am trying to have the program take input for grades and names of students and in the end output their name and grade.
Edit sorry this is my first it posting i have an error
Student.java:60: error: class, interface, or enum expected I am in java 101 so this is why it is such low level java, we only know the basics
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
and my second class is
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
} <--- error here
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
Add return statement in your multiplegradeinputs() method:
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
return null; //Add this line
}
Or change your methods to void return type if they dont return anything.
Class names have to be capitalized in java, so instead of
public class students
you should write
public class Students
Also instead of writing
keyboard.nextInt();
You should write
Integer.parseInt(keyboard.nextLine());
This is mainly because java is full of bugs and technical specifications that you won't find easily. Let me know if this fixes it for you, since you didn't post the exact error message you got.
As for the error that you pointed out, it's because your function expects a String as a return value no matter what, so either change that to void if you can or return a null string. To do that just add the following line at the very end of the method.
return null;
You should create a Student object which holds the properties of the student, e.g. Name and Grades. You should then store all the student objects in some kind of data structure such as an array list in the students class.
Adding to the answer provided by #hitz
You have a bug in the for loops:
for(int i = 1; i <multiplegradeinputs.length; i++)
for(int i = 1; i < multipleStudent.length; i++)
You will never populated multiplegradeinputs[0] and multipleStudent[0] because you start the loop at index == 1 and thus you will have only 9 student names stored instead of 10.
Change to:
for(int i = 0; i <multiplegradeinputs.length; i++)
for(int i = 0; i < multipleStudent.length; i++)
Remember even though the length in 10, the indices always start with 0 in Java and in your case will end with 9.
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public void multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
}
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
this is the 2nd class
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
You are missing a return value in the multiplegradeinputs() method.

How do you incorperate an AVERAGE and LETTERGRADE in a java program which has 2D Array

I have written a program with minimal errors but do not know where I should place the Average or Letter grade function:
package org.education.tutorial;
import java.util.Scanner;
public class GradingScale
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the number of students attending your current session :");
int numberOfStudents = keyboard.nextInt();
System.out.println();
System.out.print("Also, please enter the amount of exams taken during the duration of the course : ");
int examScores = keyboard.nextInt();
AssignValueToArray(numberOfStudents, examScores);
keyboard.close();
}
public static void AssignValueToArray(int amountOfStudents, int amountOfExams)
{
int[][] overallScore = new int[amountOfStudents][amountOfExams];
Scanner keyboardArray = new Scanner(System.in);
int numberValue = 1;
for (int index = 0; index < amountOfStudents; index++)
{
System.out.println ("\n" + "Please submit Student #" + numberValue + " 's score :" );
for(int indexOfHomeWork=0; indexOfHomeWork < amountOfExams; indexOfHomeWork++)
{
overallScore[index][indexOfHomeWork] = keyboardArray.nextInt();
}
numberValue++;
}
DisplayvalueInArray(overallScore);
keyboardArray.close();
}
public static void DisplayvalueInArray(int[][] overallScoreArray)
{
System.out.println ("The students' scores are posted below : " + "\n");
int studentCount = 1;
for (int index = 0; index < overallScoreArray.length; index++)
{
System.out.print("Grades for student " + studentCount +": ");
for (int indexOfHomeWork = 0; indexOfHomeWork < overallScoreArray[index].length;
indexOfHomeWork++)
{
System.out.print(overallScoreArray[index][indexOfHomeWork]+"\t");
}
System.out.println();
studentCount++;
}
}
I would highly recommend learning how to use variable scope and possibly objects before doing something such as this.
You never declare any variables in the class's scope.
Most of your functions don't affect anything outside their own scope, and therefore shouldn't be functions. Instead use comments to encapsulate.
Many of your variables are named poorly, instead of keyboardArray, which is not an array at all, do something like kb, or keyboardScanner
For computing average and lettergrades, think 'what am i averaging' and use that as your parameter, with the average as your return type, so something like static int average(int[] scores)

Print students in an array

I am trying to have the user type in the last name and first name of a student in an array so that I can call the student information and use it in a grade book.
The Student class has a method called Student(String last_name, String first_name)
I cannot figure out how to make it print students in a list such as:
last name, first name
last name, first name
Here is my program so far:
public static void main (String[] args)
{
System.out.println("--------------------------------");
System.out.println("Welcome to the Gradebook Program");
System.out.println("--------------------------------");
System.out.println();
students = GetNumberOfStudents();
//Allocate space for student information
Student student[] = new Student[students];
for (int i = 0; i < students; i++)
{
System.out.println("Student #" + (i+1));
System.out.print("\tEnter last name: ");
student[i] = scan.nextLine();
System.out.print("\tEnter first name: ");
student[i] = scan.nextLine();
}
System.out.println(student[i]);
I expect we would need to see the definition of Student, you have given the constructor but not the getters/setters.
I would expect the printing code to look something like
for (Student s : student) {
System.out.println(s.getLastName() + "," + s.getFirstName());
}
You are also not initialising your Student objects correctly.
Inside the loop you have written I would expect to see
new Student(lastname, firstname);
Here is a soltuion with a student class which looks like in your description.
package test; //change to your package name
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Student{
private String m_LastName;
private String m_FirstName;
private int[] TestScores = new int[3];
//Constructor
public Student(String last, String first) {
m_LastName = last;
m_FirstName = first;
}
//returns firstname
public String firstName() {
return m_FirstName;
}
//returns lastname
public String lastName() {
return m_LastName;
}
//set a test score at a given index
public void setTestScore(int index, int score) {
TestScores[index] = score;
}
//returns test score at a given index
public int testScore(int index) {
return TestScores[index];
}
//returns testscores average
public double testAverage() {
int sum = 0;
for(int i = 0; i<TestScores.length; i++) {
sum += TestScores[i];
}
return sum/TestScores.length;
}
//returns students highest test score
public int maxTestScore() {
//sort the array
for(int i = 0; i<TestScores.length; i++) {
for(int j = 0; j<TestScores.length; j++) {
if(TestScores[i]<TestScores[j]) {
int buffer;
buffer = TestScores[i];
TestScores[i] = TestScores[j];
TestScores[j] = buffer;
}
}
}
return TestScores[TestScores.length-1];
}
public boolean isPassing() {
//TODO: when hes passing?
return true;
}
public static void main (String[] args)
{
Scanner scan = new Scanner(new InputStreamReader(System.in));
System.out.println("--------------------------------");
System.out.println("Welcome to the Gradebook Program");
System.out.println("--------------------------------");
System.out.println();
/**
* dont know where you declare the students variable
* and how the getnumberofstudents function looks like
*
* students = GetNumberOfStudents();
*/
int students = 1;
List<Student> StudentList = new ArrayList<>(); //creat a list which can store student objects
for (int i = 0; i < students; i++)
{
System.out.println("Student #" + (i+1));
System.out.print("\tEnter last name: ");
String lastname = scan.nextLine(); //store lastname in a variable
System.out.print("\tEnter first name: ");
String firstname = scan.nextLine(); //store firstname in a variable
Student student = new Student(lastname, firstname); //creat new student object with the last and firstname
StudentList.add(student); //add it to the student list
}
//print out all students first and lastnames. here you can add the other data you want to print.
for (int i = 0; i < students; i++)
{
System.out.println("List of all Students:");
System.out.println("Firstname:"+StudentList.get(i).firstName()+" Lastname:"+StudentList.get(i).lastName());
}
}
}

Combining array indexes

I have created two arrays. One to store names and one to store sales. I am trying to link the indexes of each together so that index 1 from then name array will bring up the value of index 1 of the sales array. I am trying to get it to sort out the sales array and return the max sales and the person that brought in those sales. All the values are inputted by the user including the size of the arrays.
import java.util.Scanner;
import java.util.Arrays;
public class EmpArray {
public static int employee(){
Scanner input = new Scanner(System.in);
int numemp;
System.out.println("Enter how many employees to be compared: \n");
numemp = input.nextInt();
String name[] = new String[numemp];
int annsales[] = new int[numemp];
int maxannsales;
for (int i = 0; i < name.length; i++) {
System.out.println("Enter your name: \n");
String employeename = input.next();
name[i] = employeename;
System.out.println("\n");
}
for (int j = 0; j < annsales.length; j++) {
System.out.println("Enter in your annual sales: \n");
int employeesales = input.nextInt();
annsales[j] = employeesales;
System.out.println("\n");
}
System.out.println("Employee Name: " + Arrays.toString(name));
System.out.println("Total Sales: " + Arrays.toString(annsales));
Arrays.sort(annsales);
//look at page 456 of starting out with java and page 460 of the same book, p.464
System.out.println("Top Salary is : $"+annsales[annsales.length-1]);
maxannsales = annsales[annsales.length-1];
return maxannsales;
}
}
What am I doing wrong I have been at this for two weeks now.
You should make a class to store the date rather than the use two separate arrays.
public class Employee {
private int sales;
private String name;
public Employee(String name, int sales){
this.name = name;
this.sales = sales;
}
public String getName(){
return this.name;
}
public int getSales(){
return this.sales;
}
}
Now store the name and sales as local variables when you read in from your Scanner and pass them to the Employee constructor. You can then create an Employee array[] or ArrayList<Employee> and sort this array/arraylist on Employee.getSales()
Like so:
import java.util.Scanner;
import java.util.Arrays;
public class EmpArray {
public static void main(String[] args){
employee();
}
public static int employee(){
Scanner input = new Scanner(System.in);
int numEmp;
System.out.println("Enter how many employees to be compared: ");
numEmp = input.nextInt();
input.nextLine();
Employee[] employees = new Employee[numEmp];
for (int i = 0; i < numEmp; i++) {
System.out.print("Enter your name: ");
String employeeName = input.nextLine();
System.out.println();
System.out.print("Enter in your annual sales:");
int employeeSales = input.nextInt();
input.nextLine();
System.out.println();
//creates an Employee object based on the constructor defined in Employee
Employee employee = new Employee(employeeName, employeeSales);
employees[i] = employee;
}
//initialize maxSeller to first employee
Employee maxSeller = employees[0];
for(int i = 0; i < employees.length; i++){
//using the getters we created in Employee
System.out.println("Employee Name: " + employees[i].getName());
System.out.println("Total Sales: " + employees[i].getSales());
System.out.println();
//checks if employees[i] sold more than maxSeller
if(maxSeller.getSales() < employees[i].getSales()){
maxSeller = employees[i];
}
}
System.out.println();
System.out.println("Top Seller: " + maxSeller.getName());
System.out.println("Top Sales: " + maxSeller.getSales());
return maxSeller.getSales();
}
}
If you sort the array with the numbers, then that gets sorted. You can find the top or bottom sales amount, but you cannot get the name of the salesperson. The two arrays are not linked in any way, so you cannot expect sorting one to cause the sorting of the other.
You need to take an approach that is fundamentally different., using different data structures.
For instance, one approach would be to have a single Array, but not to make it of String(s) or int(s), but to store both the name and the sales together, as a pair. You could pout the pair into an object as shown by sunrize920, or you could put them both in a map.
Having paired them together into some type of object, you can then have an Array of such objects.
Then, you could sort that array. To do so, you will need to write a custom comparator.
Alternatively, keep your two arrays and don;t do any sorting. Just loop through on and find the largest number. Remember the position of the largest sales number. Then, look up the name in the other array, using the same position.

Categories

Resources