Java Class - main not compiling when i read to departments - java

I wrote the two departments and when I try to read to the class from the chief and I have a problem compiling and I can not understand what the problem is, I'd love to help.
in main the error is on the line : 5.
Main:
public class main {
public static void main(String[]args){
Lecturer LecturerObject = new Lecturer("Dani",3,"Banana",1001);
The error is here >>Lecturer[] L1 = new Lecturer("Dani",2,"Banana",1001);
College FirstCollege = new College("Hmpson",2, L1);
}
}
First Class:
public class Lecturer {
public String nameOfLecturer = "";
public int numOfTimesPenFalls = 0;
public String favoriteIceCream = "";
public int numAuto = 1000;
//constructors, same name like class
public Lecturer(String name, int TimesPenFalls, String IceCream,
int num) {
nameOfLecturer = name;
numOfTimesPenFalls = TimesPenFalls;
favoriteIceCream = IceCream;
numAuto = num;
int maxLecturer=10;
}
//Copy constructor
public Lecturer(Lecturer other){
nameOfLecturer = other.nameOfLecturer;
numOfTimesPenFalls = other.numOfTimesPenFalls;
favoriteIceCream = other.favoriteIceCream;
numAuto = other.numAuto;
}
}
Secoand Class:
public class College {
public String CollegeName = "";
public int numOfLecturers = 0;
public Lecturer[] allLecturers;
// constructors, same name like class
public College(String name, int numLecturers, Lecturer[] dataBase) {
CollegeName = name;
numOfLecturers = numLecturers;
allLecturers = dataBase;
int maxLecturer = 10;
}
// getter, only private
public String getCollegeName() {
return CollegeName;
}
// setter, only private
public void setCollegeName(String newcollegeName) {
CollegeName = newcollegeName;
}
public boolean newLecturer(Lecturer addNewLecturer, int maxLecturer) {
if (numOfLecturers < maxLecturer || numOfLecturers == maxLecturer) {
numOfLecturers += 1;
return true;
} else {
System.out.print("Sorry, Max Lecturer!");
return false;
}
}
public void sortLecturer(Lecturer[] arrAllLecturers) {
int numOfTimesPenFalls = 0;
}
}
I'm first started with java I would be happy for a detailed explanation where is the problem, thank you very much.

This statement here
Lecturer[] L1 = new Lecturer("Dani",2,"Banana",1001); is wrong because you have defined L1 as an array but you are initializing it as a simple Object....
in some IDEs like eclipse, the compiler will complain with a message like
Type mismatch: cannot convert from Lecturer to Lecturer[]
Ergo: you need to init L1 as it is, as an array:
do this:
Lecturer[] L1 = new Lecturer[]{new Lecturer("Dani",2,"Banana",1001)};
now you have an array with one Lecturer object inside..

You are trying to assign array Lecture object to array, which can be done in following manner correctly.
Lecturer[] L1 = new Lecturer[] {new Lecturer("Dani",2,"Banana",1001)};

Related

using loop variables with object variables

This is what i got
Constructor:
public class Assignment08_ {
String name;
String abrv;
int atomicNumber;
double atomicMass;
int group;
int period;
public Assignment08_(String name, String abrv, int atomicNumber, double
atomicMass, int group, int period) {
this.name = name;
this.abrv = abrv;
this.atomicNumber = atomicNumber;
this.atomicMass = atomicMass;
this.group = group;
this.period = period;
}
}
And the Class:
import java.io.File;
import java.util.Scanner;
public class Assignment08 {
public static void main(String[] args) throws Exception {
Assignment08_[] elementArr = new Assignment08_[119];
reader(elementArr);
for(int i = 0; i < args.length; i++) {
action(elementArr, args[i]);
}
}
public static void reader(Assignment08_[] elements) throws Exception {
Scanner data = new Scanner(new File("/srv/datasets/elements"));
while (data.hasNext()) {
int atomicNumber = data.nextInt();
String abrv = data.next();
String name = data.next();
double atomicMass = data.nextDouble();
int period = data.nextInt();
int group = data.nextInt();
elements[atomicNumber] = new Assignment08_(name, abrv, atomicNumber,
atomicMass, group, period);
}
data.close();
}
public static void action(Assignment08_[] element, String str) {
// for testing
System.out.printf("%s%n", element[4].abrv);
for (int i = 0; i < 119; i++) {
if (str.compareTo(element[i].abrv) == 0)
System.out.println(element[i].name);
}
}
}
i input "java Assignment08_ H" (which is equal to element[0].abrv)
i get the output:
"
Be
Exception in thread "main" java.lang.NullPointerException
at Assignment08.action(Assignment08.java:33)\
at Assignment08.main(Assignment08.java:11)
"
Be = element[4].abrv
and its wierd because if i were to take away that for statement and leave only the nested if statement and change the i to a Number (like 0), it will print the name and run properly( if i input H which equals element[0].abrv), soooo i dont know what going on here, any help would be great, thx

Issue recalling method. unsure of where im going wrong

Below is my code and I have notes beside where my errors are showing. Im unsure where I am going wrong when recalling my method or if that is even the issue.
import java.util.Scanner;
public class HurlerUse
{
static Hurler[] hurlerArray;
// find lowest score (static method)
public static int findLow(Hurler[] hurlerArray)
{
for(int i = 0; i < hurlerArray.length; i++)
{
int lowest = 0;
int index = 0;
for(int j=0; j<hurlerArray.length; j++)
{
int current = hurlerArray[i].totalPoints();// issue with my method 'totalPoints'
if(current < lowest)
{
lowest = current;
index = i;
}
}
return index;
}
}
//main code
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Hurler[] hurlerArray = new Hurler[5];
for (int i = 0; i <4; i++)
{
hurlerArray[i] = new Hurler();
System.out.println ("Enter Hurler Name:");
hurlerArray[i].setName(sc.nextLine());
hurlerArray[i].setGoalsScored(sc.nextInt());
System.out.println("Enter the hurler's goals scored");
hurlerArray[i].setPointsScored(sc.nextInt());
System.out.println("Enter the hurler's points scored");
}
for(int i=0;i< hurlerArray.length; i++)
{
hurlerArray[i] = new Hurler(MyName, MyGoalsScored, MyPointsScored);// issue with all 3 objects in the brackets but im unsure of how to fix them
}
System.out.println("The lowest scoring hurler was " + hurlerArray[findLow(hurlerArray)].getName());// error with my code here I think it is in the method
}
}//end of class
I know the nyName, myGoalsScored, myPointsScored is incorrect but can anyone explain why?
This is the class page that accompanies it
public class Hurler
{
private String name;
private int goalsScored;
private int pointsScored;
public Hurler() //constructor default
{
name ="";
goalsScored = 0;
pointsScored = 0;
}
public Hurler(String myName, int myGoalsScored, int myPointsScored) // specific constructor
{
name = myName;
goalsScored = myGoalsScored;
pointsScored = myPointsScored;
}
//get and set name
public String getMyName()
{
return name;
}
public void setName(String myName)
{
name = myName;
}
//get and set goals scored
public int getGoalsScored()
{
return goalsScored;
}
public void setGoalsScored(int myGoalsScored)
{
goalsScored = myGoalsScored;
}
// get and set points scored
public int getPointsScored()
{
return pointsScored;
}
public void setPointsScored(int myPointsScored)
{
pointsScored = myPointsScored;
}
public int totalPoints(int myGoalsScored, int myPointsScored)
{
int oneGoal = 3;
int onePoint = 1;
int totalPoints = ((goalsScored * oneGoal) + (pointsScored * onePoint));
{
return totalPoints;
}
}
}//end of class
You call totalPoints() without parameters while method totalPoints(int, int) in Hurler class expects two int parameters.
Objects MyName, MyGoalsScored, MyPointsScored are not declared at all.
You call getName() method, while in Hurler class you do not have one. There is method getMyName(), maybe you want to call that one.

Creating an ArrayList of Employees

I have three classes
employee
production workers
shift supervisor class
My idea is to make production and shift supervisor extend the employee class and then create another class, EmployeeList to fill it with information about production workers and shift supervisors.
How can i get the names and info from employee class to iterate into an arraylist?
How can i add a random list of employees more than half being prod. workers and the rest shift supervisors?
Employee:
public class Employee {
public String EmployeeName;
public String EmployeeNumber;
public int hireyear;
public double WeeklyEarning;
public Employee()
{
EmployeeName = null;
EmployeeNumber = null;
hireyear = 0;
WeeklyEarning = 0;
}
public static final String[] Enum = new String[] {
"0001-A", "0002-B","0003-C","0004-D","0002-A",
"0003-B","0004-C","0005-D","0011-A", "0012-B",
"0013-C","0014-D","0121-A", "0122-B","0123-C" };
public static final String[] Ename = new String[] {
"Josh", "Alex", "Paul", "Jimmy", "Josh", "Gordan", "Neil", "Bob",
"Shiv", "James", "Jay", "Chris", "Michael", "Andrew", "Stuart"};
public String getEmployeeName()
{
return this.EmployeeName;
}
public String getEmployeeNumber()
{
return this.EmployeeNumber;
}
public int gethireyear()
{
return this.hireyear;
}
public double getWeeklyEarning()
{
return this.WeeklyEarning;
}
public String setEmployeeName(String EName)
{
return this.EmployeeName = EName;
}
public String setEmployeeNumber(String ENumber)
{
return this.EmployeeNumber = ENumber;
}
public int setEmployeehireyear(int Ehireyear)
{
return this.hireyear = Ehireyear;
}
public double setEmployeeweeklyearning(double Eweeklyearning)
{
return this.WeeklyEarning = Eweeklyearning;
}
}
ProductionWorker:
import java.util.Random;
public class ProductionWorker extends Employee {
public double HourlyRate;
public ProductionWorker()
{
super();
HourlyRate = 0;
}
public static void main(String[] args) {
ProductionWorker pw = new ProductionWorker();
Random rnd = new Random();
int count =0;
// adding random Employees.....
while(count<5)
{
int num= rnd.nextInt(Enum.length);
int decimal = rnd.nextInt(10);
double dec = decimal/10;
pw.setEmployeeName(Ename[num]);
pw.setEmployeeNumber(Enum[num]);
pw.setEmployeehireyear(rnd.nextInt(35) + 1980);
pw.setEmployeeweeklyearning(rnd.nextInt(5000) + 5000);
pw.setHourlyRate(rnd.nextInt(44) + 6 + dec);
System.out.println("EmployeeName: " + pw.getEmployeeName() + "\nEmployeeNumber: " + pw.getEmployeeNumber() +
"\nHireYear: " + pw.gethireyear() + "\nWeeklyEarning: " + pw.getWeeklyEarning() +
"\nHourlyRate: " + pw.getHourlyRate() +"\n");
count++;
}
}
public double getHourlyRate()
{
return this.HourlyRate;
}
public void setHourlyRate(double hourlyrate)
{
this.HourlyRate = hourlyrate;
}
}
ShiftSupervisor:
import java.util.Random;
public class ShiftSupervisor extends Employee{
public double YearlySalary;
public int GoalsCleared;
public ShiftSupervisor()
{
super();
YearlySalary = 0;
}
public static void main(String[] args) {
ShiftSupervisor S = new ShiftSupervisor();
Random rnd = new Random();
int count =0;
// adding random Employees.....
System.out.println("Adding Employees..");
while(count<5)
{
int num= rnd.nextInt(Enum.length);
S.setEmployeeName(Ename[num]);
S.setEmployeeNumber(Enum[num]);
S.setEmployeehireyear(rnd.nextInt(35) + 1980);
S.setEmployeeweeklyearning(rnd.nextInt(100) * 100);
S.setYearlySalary(rnd.nextInt(40000) + 40000);
System.out.println("EmployeeName:" + S.getEmployeeName() + "\nEmployeeNumber: " + S.getEmployeeNumber() +
"\nHireYear: " + S.gethireyear() + "\nWeeklyEarning: " + S.getWeeklyEarning() +
"\nearlySalary: " + S.getYearlySalary() +"\n");
count++;
}
}
// returns yearly salary
public double getYearlySalary()
{
return this.YearlySalary;
}
// returns goals cleared
public int getGoalsCleared()
{
return this.GoalsCleared;
}
// set yearly salary
public void setYearlySalary(double yearlysalary)
{
this.YearlySalary = yearlysalary;
}
}
The first thing I would do is have all necessary fields set in the constructor. If an Employee doesn't "exist" until it has a name, then that should be part of the constructor.
Then, I would suggest you consider renaming some of your fields. When I first saw Enum as a String[] and highlighted as a type, it took me a moment to figure out what exactly was going on. Renaming it to employeeNumbers could solve this.
Next, I think you should have an EmployeeGenerator class whose sole purpose is generating Employees.
public class EmployeeGenerator {
public ProductionWorker generateProductionWorker() {
Random rng = new Random();
int numberOfEmployeeNames = employeeNames.length;
String employeeName = employeeNames[rng.nextInt(numberOfEmployeeNames)];
int numberOfEmployeeNumbers = employeeNumbers.length;
String employeeNumber = employeeNumbers[rng.nextInt(numberOfEmployeeNumbers)];
ProductionWorker worker = new ProductionWorker(employeeName, employeeNumber);
int yearHired = rng.nextInt(100) + 1900;
worker.setHireYear(yearHired);
int hourlyRate = rng.nextInt(20) + 10;
worker.setHourlyRate(hourlyRate);
// any other fields...
return worker;
}
// method to generate shift supervisor
}
And then you can simply do
public static void main(String[] args) {
Random rng = new Random();
int numberOfEmployeesToGenerate = 1000;
int minimumNumberOfProductionWorkers = numberOfEmployeesToGenerate / 2;
int numberOfProductionWorkersToGenerate =
minimumNumberOfProductionWorkers + rng.nextInt(100);
int numberOfSupervisorsToGenerator =
numberOfEmployeesToGenerate - numberOfProductionWorkersToGenerate;
List<Employee> employees = new ArrayList<>();
EmployeeGenerator generator = new EmployeeGenerator();
for (int i = 0; i < numberOfProductionWorkersToGenerate; i++) {
ProductionWorker worker = generator.generateProductionWorker();
employees.add(worker);
}
for (int i = 0; i < numberOfSupervisorsToGenerate; i++) {
Supervisor supervisor = generator.generateSupervisor();
employees.add(supervisor);
}
}
This should hopefully give you a point in the right direction. This isn't perfect code, and there are other ways to refactor this to make it more maintainable and performant.
When you say you want to add a random list of employees, What do you mean exactly?
Currently you instantiate only one ProductionWorker and one ShiftSupervisor, change the values of the member variables, and print some text to StdOut.
Do you want to store instances in a list or is the console output sufficient?
Also, you have two main-methods. Which one will be performed? It might be better to have one Main class as an entry point for your application and from there create the instances.
In general you can do something like that:
public class Main {
public static void main(String[] args) {
List<Employee> emps = new ArrayList<>();
for (int i = 0; i < 5; i++) {
//create new employee
emps.add(newEmployee);
}
//do something with list
}
}

make a global object in java

I want to make an array of objects and use it in different functions. I wrote this pseudocode
privat stock[] d;
privat stock example;
public void StockCheck(){
d =new stock[2];
d[0]= new stock("a","test1", 22);
d[1]= new stock("b","test2", 34);
}
#Override
public stock getStock(String name) throws StockCheckNotFoundException{
int i;
System.out.println("ok" + name + d.legth); // error
example = new stock("example","example",2);
return example;
}
In class test I make an instance of getStock and I call the function getStock stock.getStock();
I get a NullPointerExeption when I do d.length. d is null but I don't understand why.
Hmmmm. If that is in any way like your real code, then the problem is that your "constructor" isn't really a constructor, as you've declared it to return void, making it an ordinary method instead. Remove tbat "void" and it may fix the problem!
Perhaps this example of code will do what you need, using three classes
Test - the main test code
Stock - the implied code for Stock from your question
StockCheck - the corrected code from your question.
(Note: you may really want to use an ArrayList inside StockQuote so you can add and delete Stocks.)
Test class
package stackJavaExample;
public class Test {
public static void main(String[] args) {
String[] testNames = {"test1","test2","notThere"};
StockCheck mStockCheck = new StockCheck();
for (int i=0; i<testNames.length; i++) {
Stock result = mStockCheck.getStock(testNames[i]);
if (result == null) {
System.out.println("No stock for name: " + testNames[i]);
} else {
System.out.println("Found stock: " + result.getName() + ", " + result.getSymbol() + ", " + result.getValue());
}
}
}
}
Stock class
package stackJavaExample;
public class Stock {
private String symbol;
private String name;
private double value;
public Stock(String symbol, String name, double value) {
this.symbol = symbol;
this.name = name;
this.value = value;
}
public String getSymbol() { return symbol;}
public String getName() { return name;}
public double getValue() {return value;}
}
StockCheck class
package stackJavaExample;
public class StockCheck {
private Stock[] d;
public StockCheck() {
d = new Stock[2];
d[0] = new Stock("a","test1", 22);
d[1] = new Stock("b","test2", 34);
}
public Stock getStock(String name) {
for (int i=0; i < d.length; i++) {
if (d[i].getName().equalsIgnoreCase(name)) {
return d[i];
}
}
return null;
}
}

Problem in arranging contents of Class in JAVA

I have some classes and I'm trying to fill the objects of this class. Here is what i've tried. (Question is at the below)
public class Team
{
private String clubName;
private String preName;
private ArrayList<String> branches;
public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<String>();
}
public Team() {
// TODO Auto-generated constructor stub
}
public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public ArrayList<String> getBranches() { return branches; }
public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(ArrayList<String> branches) { this.branches = branches; }
}
public class Branch
{
private ArrayList<Player> players = new ArrayList<Player>();
String brName;
public Branch() {}
public void setBr(String brName){this.brName = brName;}
public String getBr(){return brName;}
public ArrayList<Player> getPlayers() { return players; }
public void setPlayers(ArrayList<Player> players) { this.players = players; }
}
//TEST CLASS
public class test {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
String a,b,c;
String q = "q";
int brCount = 0, tCount = 0;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
Team[] teams = new Team[30];
Branch[] myBranch = new Branch[30];
for(int z = 0 ; z <30 ;z++)
{
teams[z] = new Team();
myBranch[z] = new Branch();
}
ArrayList<String> tmp = new ArrayList<String>();
int k = 0;
int secim = Integer.parseInt(input.readLine());
while(secim != 0)
{
if(k!=0)
secim = Integer.parseInt(input.readLine());
k++;
switch(secim)
{
case 1 :
brCount = 0;
a = input.readLine();
teams[tCount].setClubName(a);
b= input.readLine();
teams[tCount].setPreName(b);
c = input.readLine();
while(c.equals(q) == false)
{
if(brCount != 0)
{c = input.readLine();}
if(c.equals(q)== false){
myBranch[brCount].brName = c;
tmp.add(myBranch[brCount].brName);
brCount++;
}
System.out.println(brCount);
}
teams[tCount].setBranches(tmp);
for(int i=0;i<=tCount;i++ ){
System.out.print("a :" + teams[i].getClubName()+ " " + teams[i].getPreName()+ " ");
System.out.println(teams[i].getBranches());}
tCount++;
break;
case 2:
String src = input.readLine();//LATERRRRRRRr
}
}
}
}
The problem is one of my class elements. I have an arraylist as an element of a class.
When i enter:
AAA as preName
BBB as clubName
c
d
e as Branches
Then as a second element
www as preName
GGG as clubName
a
b as branches
The result is coming like:
AAA BBB c,d,e,a,b
GGG www c,d,e,a,b
Which means ArrayList part of the class is putting it on and on. I tried to use clear() method but caused problems. Any ideas.
The problem is that the two Team objects are sharing the same reference to a single ArrayList<String>. There are many ways to solve this, but one way is to let Team manage its own List<Branch>, and it should only expose an add(Branch) instead of setBranches(List<Branch>). This would hide most information from the client, exposing only the most essential functionalities, which is a good thing.
Note also that I use the interface List<Branch> instead of ArrayList<Branch> (or ArrayList<String>). This is in accordance with Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces.
I also recommend using java.util.Scanner for the I/O. Look at the API for examples, and there are many questions on stackoverflow about it as well. It'd make the code much simpler.
You need to copy lists in setters, otherwise you are using the same list (tmp) everywhere, so no wonder it has the same contents:
public void setBranches(List<String> branches) {
this.branches = new ArrayList<String>(branches);
}
public void setPlayers(List<Player> players) {
this.players = new ArrayList<Player>(players);
}
Theoretically, you also need to copy or wrap it in getters, but that's another story.

Categories

Resources