I have three classes: Main,ReusaxCorp and Employee. Let's get straight to the point: In the ReusaxCorp class I want to implement two methods: retrieveEmployee, which iterates through the Array List and prints out all employees information. So I tried this:
public void retrieveEmployee() {
for (int i = 0; i < employees.size(); i++) {
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "salary: " + employee.grossSalary);
}
}
But that does not work, because I can't access - for instance - employee.ID or employee.name. In the second method. updateEmployee I would have liked to change the information, but that doesn't work either because of the accessibility. I appreciate any kind of help. Here are my three classes:
public class Employee {
protected String ID;
protected String name;
protected double grossSalary;
final String END_OF_LINE = System.lineSeparator();
public Employee (String ID, String name, double grossSalary){
this.ID = ID;
this.name = name;
this.grossSalary = grossSalary;
}
public double getGrossSalary() {
return grossSalary;
}
public void setGrossSalary(double grosssalary) {
this.grossSalary = grossSalary;
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here's my Main class:
public class Main {
private static String END_LINE;
private Scanner sc;
public String name;
public String ID;
public double salary;
private int GPA;
private ReusaxCorp reusaxcorp;
public Main(){
sc = new Scanner(System.in);
END_LINE = System.lineSeparator();
}
public void presentoptions(){
while (true){
System.out.println("=== Welcome === ");
System.out.println("Choose an option below: ");
System.out.println(" ");
System.out.println("1. Register an employee. ");
System.out.println("2. Remove an employee. ");
System.out.println("3. Retrieve an employees information. ");
int option = sc.nextInt();
switch (option) {
case 1:
System.out.println("What type of employee? " + END_LINE
+ " - Intern. " + END_LINE
+ " - Employee. " + END_LINE
+ " - Manager. " + END_LINE
+ " - Director." + END_LINE);
String type = sc.nextLine();
createEmployee();
break;
case 2:
break;
case 3:
reusaxcorp.retrieveEmployee();
break;
default:
System.out.println("Error. Please try again.");
break;
}
}
}
public void createEmployee(){
String typeofemployee = sc.nextLine();
System.out.println("What's the ID of the new " + typeofemployee + "?");
ID = sc.nextLine();
System.out.println("What's the name of the new " + typeofemployee + "?");
name = sc.nextLine();
System.out.println("What's the salary of the new " + typeofemployee + "?");
salary = sc.nextDouble();
Employee employee = new Employee(ID, name, salary);
switch (typeofemployee) {
case "Intern":
System.out.println("What's the new Interns GPA? ");
GPA = sc.nextInt();
case "Employee":
break;
case "Manager":
break;
case "Director":
break;
default:
System.out.println("Error");
break;
}
}
public static void main(String[] args) {
Main runcode = new Main();
runcode.presentoptions();
}
}
And here at last the ReusaxCorp class.
public class ReusaxCorp extends Main {
ArrayList<Employee> employees = new ArrayList<Employee>();
final String END_OF_LINE = System.lineSeparator();
public void registerEmployee(){
employees.add(new Employee(ID, name, salary));
}
public void retrieveEmployee() {
for (int i = 0; i < employees.size(); i++) {
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "salary: " + employee.grossSalary);
}
}
public void updateEmployee(){
}
}
You are trying to access the variable employee which does not exist anywhere int the class.
public void retrieveEmployee() {
for (int i = 0; i < employees.size(); i++) {
//add this line
Employee employee = employees.get(i);
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "salary: " + employee.salary);
}
}
You can also use a for-each loop:
for(Employee employee: employees){
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "salary: " + employee.salary);
}
Also note that accessing the fields such as ID using employee.ID is only applicable if the classes are in the same package (being protected). Otherwise you need to create a getter and access them using getter such as employee.getID()
Use employee.getId() instead of employee.ID while iterating through the list of employees, you already have those public getter methods implemented while the class members are protected. Do so for the other class members (name and so on) as well…
You can do that in your solution by getting the employee from the list by index like
System.out.println(employees.get(i).getId());
or you just take a "for each" loop like
for (Employee employee : employees) {
System.out.println(employee.getId());
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have code that has several classes with different cars and some classes. Below is my code, I'm not sure why vanClass van; is not working as it is basically a copy paste of the past classes that work. Any help is appreciated. To clarify, I am only having problems with the last few lines of the autopark class where I initiate vanClass as van and go from there.
import java.util.*;
class sedan {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public sedan(String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
return main;
}
}
class SUV {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
String carries;
public SUV(String initMake, String initModel, String initColor, int initYear, double initPrice, boolean initFourWD){
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
fourWD = initFourWD;
}
public String toString() {
String name = "SUV";
String main = new String();
if (fourWD) {
main = ("4WD " + color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
else {
main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
return main;
}
}
class truckClass {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public truckClass(String initMake, String initModel, int initYear, double initPrice, boolean initisheavyDuty, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isheavyDuty = initisheavyDuty;
carries = initCarries;
}
public String toString() {
String name = "Truck";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
return main;
}
class vanClass {
String make;
String model;
int year;
double price;
boolean isCovered;
String carries;
public vanClass(String initMake, String initModel, int initYear, double initPrice, boolean initisCovered, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isCovered = initisCovered;
carries = initCarries;
}
public String toString() {
String name;
String main;
if (isCovered()){
name = "covered Van";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
else {
name = "Van";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
return main;
}
}
public class autoPark {
public static void main(String args[]) {
sedan sedan1; // declaring cars object by name sedan1
sedan1 = new sedan("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford" , "Model-1" , "white" , 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
truckClass truck; //declaring cars object by name truck
truck = new truckClass("Ford" , "Model-1" , 2015, 20000, true, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
vanClass van;
van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2";
System.out.println(van);
}
}
I came across 4 issues
missing } just before starting vanClass
missing ) after van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2");
extra pair of parenthesis after isCovered which is a member data instead of method
Declaring main as String twice inside the toString method of SUV class
import java.util.*;
class sedan {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public sedan(String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
return main;
}
}
class SUV {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
String carries;
public SUV(String initMake, String initModel, String initColor, int initYear, double initPrice, boolean initFourWD){
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
fourWD = initFourWD;
}
public String toString() {
String name = "SUV";
String main = new String();
if (fourWD) {
main = ("4WD " + color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
else {
main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
return main;
}
}
class truckClass {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public truckClass(String initMake, String initModel, int initYear, double initPrice, boolean initisheavyDuty, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isheavyDuty = initisheavyDuty;
carries = initCarries;
}
public String toString() {
String name = "Truck";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
return main;
}
}
class vanClass {
String make;
String model;
int year;
double price;
boolean isCovered;
String carries;
public vanClass(String initMake, String initModel, int initYear, double initPrice, boolean initisCovered, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isCovered = initisCovered;
carries = initCarries;
}
public String toString() {
String name;
String main;
if (isCovered){
name = "covered Van";
main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
else {
name = "Van";
main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
return main;
}
}
public class autoPark {
public static void main(String args[]) {
sedan sedan1; // declaring cars object by name sedan1
sedan1 = new sedan("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford" , "Model-1" , "white" , 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
truckClass truck; // declaring cars object by name truck
truck = new truckClass("Ford" , "Model-1" , 2015, 20000, true, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
vanClass van;
van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2");
System.out.println(van);
}
}
You need to consider using inheritance as mentioned by others.
I fixed and refactored your class using inheritance:
abstract class Vehicle{
protected String maker;
protected String model;
protected int year;
protected double price;
public Vehicle(String maker, String model, int year, double price) {
this.maker=maker;
this.model=model;
this.year=year;
this.price=price;
}
abstract String getType();
#Override
public String toString() {
return maker + " " + model + " " + getType() + " (" + year + ") costs $" + price;
}
}
abstract class HeavyVehicle extends Vehicle{
protected String carries;
public HeavyVehicle(String maker, String model, int year, double price, String carries) {
super(maker, model, year, price);
this.carries=carries;
}
}
class SUV extends HeavyVehicle{
String color;
boolean fourWD;
public SUV(String maker, String model, String initColor, int year, double price,
boolean initFourWD) {
super(maker,model,year,price,"1");
color = initColor;
fourWD = initFourWD;
}
public String toString() {
StringBuilder sb = new StringBuilder();
if (fourWD) {
sb.append("4WD ");
}
sb.append(color + " " + super.toString());
return sb.toString();
}
#Override
String getType() {
return "SUV";
}
}
class Truck extends HeavyVehicle{
public Truck(String maker, String model, int year, double price,String carries) {
super(maker,model,year,price,carries);
}
public String toString() {
return maker + " " + model + " " + getType() + " (" + year + ") carries" + carries + " costs $" + price;
}
#Override
String getType() {
return "Truck";
}
}
class Van extends HeavyVehicle{
boolean isCovered;
public Van(String maker, String model, int year, double price, boolean isCovered, String carries){
super(maker,model,year,price,carries);
this.isCovered = isCovered;
}
public String toString() {
String name = isCovered ? "covered Van" : getType();
return maker + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price;
}
#Override
String getType() {
return "Van";
}
}
class Sedan extends Vehicle{
String color;
public Sedan(String maker, String model, String color, int year, double price) {
super(maker,model,year,price);
this.color = color;
}
#Override
public String toString() {
return color + " " + super.toString();
}
#Override
String getType() {
return "Sedan";
}
}
public class Main {
public static void main(String args[]) {
Sedan sedan1; // declaring cars object by name sedan1
sedan1 = new Sedan("Ford", "Model-1", "white", 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford", "Model-1", "white", 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
Truck truck; // declaring cars object by name truck
truck = new Truck("Ford", "Model-1", 2015, 20000, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
Van van;
van = new Van("Ford", "Model-1", 2015, 20000, true, "2");
System.out.println(van);
}
}
Was missing a } and ). Silly mistake
I am currently working on a project where I read in a CSV file that contains a list of Pokemon, as well as their traits. I am trying to run a battle simulator that randomly pairs up these Pokemon with each other and compares their combatScore, which is a result of a simple calculation using their traits such as speed, attack, defense, etc. I read in all of the Pokemon from the CSV file into an ArrayList of type Pokemon. Now, I want to randomly pair them up with each other and compare their combatScore; whoever has the higher score moves on to the next round, and the loser is placed into another ArrayList of defeated Pokemon. However, I do not know how to randomly pair up the Pokemon. Here is my code of the main class so far:
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
public class assign1 {
public static void main(String[] args) throws IOException {
String csvFile = args[0]; //path to CSV file
String writeFile = args[1]; //name of output file that contains list of Pokemon and their traits
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<Pokemon> population = new ArrayList<Pokemon>();
FileWriter fileWriter = new FileWriter(writeFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
try {
br = new BufferedReader(new FileReader(csvFile));
String headerLine = br.readLine(); // used to read first line of CSV file that contains headers
while ((line = br.readLine()) != null) {
Pokemon creature = new Pokemon();
// use comma as separator
String[] pokemon = line.split(cvsSplitBy);
creature.setId(pokemon[0]);
creature.setName(pokemon[1]);
creature.setType1(pokemon[2]);
creature.setType2(pokemon[3]);
creature.setTotal(pokemon[4]);
creature.setHp(Integer.parseInt(pokemon[5]));
creature.setAttack(Integer.parseInt(pokemon[6]));
creature.setDefense(Integer.parseInt(pokemon[7]));
creature.setSpAtk(Integer.parseInt(pokemon[8]));
creature.setSpDef(Integer.parseInt(pokemon[9]));
creature.setSpeed(Integer.parseInt(pokemon[10]));
creature.setGeneration(Integer.parseInt(pokemon[11]));
creature.setLegendary(Boolean.parseBoolean(pokemon[12]));
creature.getCombatScore();
// Adds individual Pokemon to the population ArrayList
population.add(creature);
// Writes to pokemon.txt the list of creatures
bufferedWriter.write(creature.getId() + ". "
+ "Name: " + creature.getName() + ": "
+ "Type 1: " + creature.getType1() + ", "
+ "Type 2: " + creature.getType2() + ", "
+ "Total: " + creature.getTotal() + ", "
+ "HP: " + creature.getHp() + ", "
+ "Attack: " + creature.getAttack() + ", "
+ "Defense: " + creature.getDefense() + ", "
+ "Special Attack: " + creature.getSpAtk() + ", "
+ "Special Defense: " + creature.getSpDef() + ", "
+ "Speed: " + creature.getSpeed() + ", "
+ "Generation: " + creature.getGeneration() + ", "
+ "Legendary? " + creature.isLegendary() + ", "
+ "Score: " + creature.getCombatScore());
bufferedWriter.newLine();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
bufferedWriter.close();
}
}
And here is the code for my Pokemon class:
public class Pokemon {
String id;
String name;
String type1;
String type2;
String total;
int hp;
int attack;
int defense;
int spAtk;
int spDef;
int speed;
int generation;
boolean legendary;
public Pokemon() {}
public String getId () {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType1() {
return type1;
}
public void setType1(String type1) {
this.type1 = type1;
}
public String getType2() {
return type2;
}
public void setType2(String type2) {
this.type2 = type2;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
public int getSpAtk() {
return spAtk;
}
public void setSpAtk(int spAtk) {
this.spAtk = spAtk;
}
public int getSpDef() {
return spDef;
}
public void setSpDef(int spDef) {
this.spDef = spDef;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getGeneration() {
return generation;
}
public void setGeneration(int generation) {
this.generation = generation;
}
public boolean isLegendary() {
return legendary;
}
public void setLegendary(boolean legendary) {
this.legendary = legendary;
}
public int getCombatScore() {
return (speed/2) * (attack + (spAtk/2)) + (defense + (spDef/2));
}
#Override
public String toString() {
return "Name: " + this.getName()
+ ", Type 1: " + this.getType1()
+ ", Type 2: " + this.getType2()
+ ", Total: " + this.getTotal()
+ ", HP: " + this.getHp()
+ ", Attack: " + this.getAttack()
+ ", Defense: " + this.getDefense()
+ ", Sp. Attack: " + this.getSpAtk()
+ ", Sp. Defense: " + this.getSpDef()
+ ", Generation: " + this.getGeneration()
+ ", Legnedary: " + this.isLegendary()
+ ", Score: " + this.getCombatScore();
}
}
I only want to compare their combatScore values to each other. Any help/suggestions would be much appreciated.
What come to my mind is this. You pick one random item (pokemon) from array list. Remove it from array list. Then you pick one random item again and remove it. Now you have a pair of items. Repeat above step for remaining items in array list until no more items available.
Or you can shuffle whole array list first and then pick item i and item i+1 as pair for i=0,2,4,6,...
Collections.shuffle(pokemonsArrayList);
for (int i=0; i< pokemonsArrayList.size(); i+=2) {
pokemon1 = pokemonsArrayList.get(i);
pokemon2 = pokemonsArrayList.get(i+1);
}
Just make sure that number of elements in ArrayList is even. Otherwise code above will throw exception index out of bound
Since every element in an ArrayList has an index, you can just get a random element from it by calling
Pokemon pokemon1;
Pokemon pokemon2;
pokemon1 = arrayList.get(Math.random()*arrayList.size());
do {
pokemon2 = arrayList.get(Math.random()*arrayList.size());
} while(pokemon1.getId() == pokemon2.getId());
then compare the Pokémon you got out of List1 with the one you got from List2.
You can then of course remove the Pokémon from the List if you wish.
Hope that helps you out!
I am trying to display certifications done by an employee. In one array say "certificates" I am holding certificates entered while creating the employee. Now I want my employee to update his "certificates" by adding the certifications to the same array. And i want to display the total certifications list done by the employee after updating. Here is my code bit
{
private String FirstName, LastName;
protected float salary;
private char grade;
private int empid;
private static int i;
private int j;
private Date1 dt; //*//
private int experience;
private String designation;
final String var1 = "YES";
String var2;
Scanner enterCertificate = new Scanner(System.in);
private String[] certificate = new String[]{};
// CONSTRUCT
public Employee(String nmf, String nml, float sal, char gd, Date1 dt, int experience, String designation, String[] certificate)
{
FirstName = nmf;
LastName = nml;
salary = sal;
this.dt = dt; //*//
grade = gd;
this.experience = experience;
this.designation = designation;
this.certificate = certificate;
empid = ++i;
}
// DISPLAY
public void display()
{
System.out.println("Employee"+empid+ " Complete Details : ");
System.out.print('\n');
System.out.println("Employee FirstName is " + FirstName);
System.out.println("Employee LastName is " + LastName);
System.out.println("Employee Salary is Rs." + salary);
System.out.println("Employee Grade is " + grade);
System.out.print("Joining Date is ");
dt.DateDisplay();
System.out.println("Employee experience is " + experience + " Years");
System.out.println("Employee Designation is " + designation);
}
public String[] updateCertificate()
{
System.out.println("Do you want to update certification ? YES/NO");
Scanner scanner3 = new Scanner(System.in);
var2 = scanner3.nextLine();
if(var1.equalsIgnoreCase(var2))
{
System.out.println("Enter Certification Details for any Updates: ");
this.certificate[j] = enterCertificate.nextLine();
}
else
{
return null;
}
return certificate;
}
public String toString()
{
return FirstName + ", " + "Employee ID: " + empid + ", " + experience + " Years Experience"+ ", " + designation + ", " + "Certification: " + certificate[j]+ ".";
}
// ID DISPLAY
public static void count()
{
System.out.println("Total number of employees is " + i);
}
#Override
public String[] displayUpdateCertificate()
{
String[] displaycertificate = new String[5];
displaycertificate = certificate;
if(var1.equalsIgnoreCase(var2))
{
System.out.println("Displaying updated certificate List.....");
System.out.println(Arrays.toString(certificate));
}
else
{
System.out.println("No Certificates were updated....");
}
return displaycertificate;
}
}
My main class goes like this.....
public static void main(String[] args)
{
Date1 dt = new Date1(12,11,2015); //*//
Employee emp1,emp2,emp3,emp4,emp5;
emp1 = new ProjectManager("MaheshKumar","Siddaraju",16700,'A',dt, 7, "Project Manager",new String[] {"PMI"}); // To input array as parameter new String[] form is used
((ProjectManager)emp1).ProjectManagerDisplay(); //Downcasting
emp2 = new ContractTechnicalAssociate("Mohammad","Javeed",0,'A',dt, 5, "Contract based Technical Associate",new String[] {"SCJP"});
((ContractTechnicalAssociate)emp2).ContractTechnicalAssociateDisplay();
emp3 = new TechnicalAssociate("Aruna","Daggubati",16700,'A',dt, 6, "Technical Associate",new String[] {"SCJP"});
((TechnicalAssociate)emp3).TechnicalAssociateDisplay();
emp4 = new ProjectManager("Kiran","Vadlamudi",16700,'A',dt, 4, "Project Manager",new String[] {"PMI"});
((ProjectManager)emp4).ProjectManagerDisplay();
emp5 = new TechnicalAssociate("Neenu","Sebastian",16700,'A',dt, 9, "TechnicalAssociate",new String[] {" "});
((TechnicalAssociate)emp5).TechnicalAssociateDisplay();
Employee.count();
scanner = new Scanner(System.in);
int i;
while(true)
{
System.out.println("Enter EmployeeID to get Employee short details : ___ ");
i = scanner.nextInt();
System.out.println("Employee ID entered is: " + i);
System.out.println("Fetching Employee Details......" + '\n');`
So i want to add the updated certificates with these from the main class
You should use ArrayList or make arraycopy to new array with length+1.
So I had to create a method that separated input string into first/middle/last names, counted the number of "students" created, etc, and then I had to create a class that tested those methods.
public void setName(String newName)
{
String[] nameInput = newName.split(" ");
if(nameInput.length == 0)
{
System.out.println("Error, please enter at least two names.");
newName = null;
}
else if(nameInput.length == 1)
{
firstName = nameInput[0];
middleName = "";
lastName = nameInput[1];
newName = firstName + lastName;
}
else if(nameInput.length == 2)
{
firstName = nameInput[0];
middleName = nameInput[1];
lastName = nameInput[2];
newName = firstName + middleName + lastName;
}
else
{
System.out.println("Error! You can only enter up to three names.");
}
}
public String getName()
{
if (middleName == null)
{
return firstName + " " + lastName;
}
else
return firstName + " " + middleName + " " + lastName;
}
public String getId()
{
return identifier = generateID();
}
#Override
public String toString()
{
return getName() + "\n" + "(" + generateID() + ")";
}
private String generateID()
{
return UUID.randomUUID().toString();
}
and this is the way I am testing the code:
public static void testStudent()
{
System.out.println("Trying to create testStudent1 with a single name...");
testStudent1 = new Student("A");
System.out.println("testStudent1.toString() is " + testStudent1.toString());
System.out.println("testStudent1.getFirstName() is " + testStudent1.getFirstName());
System.out.println("testStudent1.getMiddleName() is " + testStudent1.getMiddleName());
System.out.println("testStudent1.getLastName() is " + testStudent1.getLastName());
System.out.println("Trying to create testStudent2 with two names...");
testStudent1 = new Student("A B");
System.out.println("testStudent2.toString() is " + testStudent2.toString());
System.out.println("testStudent2.getFirstName() is " + testStudent2.getFirstName());
System.out.println("testStudent2.getMiddleName() is " + testStudent2.getMiddleName());
System.out.println("testStudent2.getLastName() is " + testStudent2.getLastName());
System.out.println("Trying to create testStudent3 with three names...");
testStudent1 = new Student("A B C");
System.out.println("testStudent3.toString() is " + testStudent3.toString());
System.out.println("testStudent3.getFirstName() is " + testStudent3.getFirstName());
System.out.println("testStudent3.getMiddleName() is " + testStudent3.getMiddleName());
System.out.println("testStudent3.getLastName() is " + testStudent3.getLastName());
}
I keep running into a null pointer exceptions when it tests toString for a student with 2 names, and I have no clue why.
Edit: The issue is with the testStudent variable in the testStudent() method.
System.out.println("Trying to create testStudent1 with a single name...");
testStudent1 = new Student("A");
System.out.println("testStudent1.toString() is " + testStudent1.toString());
System.out.println("testStudent1.getFirstName() is " + testStudent1.getFirstName());
System.out.println("testStudent1.getMiddleName() is " + testStudent1.getMiddleName());
System.out.println("testStudent1.getLastName() is " + testStudent1.getLastName());
System.out.println("Trying to create testStudent2 with two names...");
Student testStudent2 = new Student("A B");
System.out.println("testStudent2.toString() is " + testStudent2.toString());
System.out.println("testStudent2.getFirstName() is " + testStudent2.getFirstName());
System.out.println("testStudent2.getMiddleName() is " + testStudent2.getMiddleName());
System.out.println("testStudent2.getLastName() is " + testStudent2.getLastName());
System.out.println("Trying to create testStudent3 with three names...");
Student testStudent3 = new Student("A B C");
System.out.println("testStudent3.toString() is " + testStudent3.toString());
System.out.println("testStudent3.getFirstName() is " + testStudent3.getFirstName());
System.out.println("testStudent3.getMiddleName() is " + testStudent3.getMiddleName());
System.out.println("testStudent3.getLastName() is " + testStudent3.getLastName());
Since you are re-using the testStudent1 variable to create a new Object of Student class and not using them to invoke getter functions, it will throw an NPE for testStudent2 and testStudent3 variables.
Answer for old issue: The issue is with your while statement. It will never stop.
You can just find out the count by doing nameInput.length for the String array.
It should be like this:
String[] nameInput = newName.split(" ");
if (nameInput.length == 1)
{
System.out.println("Error, please enter at least two names.");
newName = null;
}
else if (nameInput.length == 2)
{
...
}
else if (nameInput.length == 3)
{
...
}
else
{
...
}
You could use StringTokenizer class to help you with this.
import java.util.StringTokenizer
StringTokenizer test = new StringTokenizer("An example string");
while (test.hasMoreTokens()) {
System.out.println(test.nextToken());
}
Output:
An
example
string.
The countTokens() method can provide how many tokens a string will provide prior processing. That way you will know if you have a middle name or not.
please check trim() method
public static void getName(String newName) {
newName = newName.trim();
String fullName = null;
String[] nameInput = newName.split(" ");
switch (nameInput.length) {
case 2:
fullName = mergeName(nameInput[0], "", nameInput[1]);
break;
case 3:
fullName = mergeName(nameInput[0], nameInput[1], nameInput[2]);
break;
default:
System.out.println("Error, please enter at least two names.");
break;
}
System.out.println(fullName);
}
public static String mergeName(String firstName, String middleName,
String lastName) {
String name = firstName+" " + middleName+" " + lastName;
return name;
}
This is where I am printing out and I need it to print in columns.aLeaderboard is an array list with a custom class.it contains several different ints
System.out.println("Position Team Games Played Home Wins Home Draws Home Losses Home Goals For Home Goals Against Away Wins Away Draws Away Losses Away Goals For Away Goals Against Goal Difference Total Points");
for(int counter = 0;counter<teamName.size();counter++)
{
System.out.print((counter + 1) + " " + teamName.get(counter) + " " + (aLeaderboard.get(counter)).getGamesPlayed() + " " + (aLeaderboard.get(counter)).getHomeWins() + " " + (aLeaderboard.get(counter)).getHomeDraws() + " ");
System.out.print((aLeaderboard.get(counter)).getHomeLosses() + " " + (aLeaderboard.get(counter)).getAwayWins() + " " + (aLeaderboard.get(counter)).getAwayWins() + " " + (aLeaderboard.get(counter)).getAwayDraws() + " ");
System.out.print((aLeaderboard.get(counter)).getHomeGoalsFor() + " " + (aLeaderboard.get(counter)).getHomeGoalsAgainst() + " " + (aLeaderboard.get(counter)).getAwayLosses() + " " + (aLeaderboard.get(counter)).getGamesPlayed() + " ");
System.out.print((aLeaderboard.get(counter)).getAwayGoalsFor() + " " + (aLeaderboard.get(counter)).getAwayGoalsAgainst() + " " + (aLeaderboard.get(counter)).getGoalsDifference() + " " + (aLeaderboard.get(counter)).getTotalPoints());
System.out.println();
}
I would use System.out.printf(...) and use a template String to help be sure that all columns line up. Then you could print things out easily in a for loop.
For example:
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class Foo4 {
public static void main(String[] args) {
List<Bar4> bar4List = new ArrayList<>();
bar4List.add(new Bar4("Donald", 3, "A", 22.42));
bar4List.add(new Bar4("Duck", 100, "B", Math.PI));
bar4List.add(new Bar4("Herman", 20, "C", Math.sqrt(20)));
String titleTemplate = "%-10s %6s %6s %9s%n";
String template = "%-10s %6d %6s %9s%n";
System.out.printf(titleTemplate, "Name", "Value", "Grade", "Cost");
for (Bar4 bar4 : bar4List) {
System.out.printf(template, bar4.getName(),
bar4.getValue(), bar4.getGrade(), bar4.getCostString());
}
}
}
class Bar4 {
private String name;
private int value;
private String grade;
private double cost;
private NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
public Bar4(String name, int value, String grade, double cost) {
this.name = name;
this.value = value;
this.grade = grade;
this.cost = cost;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public String getGrade() {
return grade;
}
public double getCost() {
return cost;
}
public String getCostString() {
return currencyFormat.format(cost);
}
}
Which would return:
Name Value Grade Cost
Donald 3 A $22.42
Duck 100 B $3.14
Herman 20 C $4.47
For more details on the user of the String format specifiers (i.e., the %6d and %6s above), please look at the Formatter API.