Passing arrays into testclass constructors - java

I need to pass a 1d array that isn't defined in a method.
I need to create a testclass then make the arrays myself.
I'm just not sure about the syntax.
Example, here's my company class:
public class Company
{
String name;
String address;
Employee employeeList[] = new Employee[3];
public Company (String name, String address ,
Employee employeeList, String jobTitle )
{
this.name = name;
this.address = address;
}
public void printDetails()
{
for(int i = 0; i>employeeList.length;i++)
{
System.out.println(" The companys name is " + name);
System.out.println(" The Companys Address is "+ address);
System.out.println("The List of employees are " + employeeList[i].name);
System.out.println("The Titles of These Employees are " + employeeList[i].jobTitle);
}
}
}
But my testclass is where the problem lies.
Where do I go from here? Do do I put arrays(employees) into it?
public class TestCompany
{
public static void main(String[] args)
{ employees?
Company hungryBear = new Company("hungryBear ", "Those weird apartments ",////// );
}
}

public Company (String name, String address ,
Employee employeeList, String jobTitle )
Should be:
public Company (String name, String address ,
Employee []employeeList, String jobTitle )
Right now, you're not passing an array to your method, your passing an instance. You need to tell Java that you're passing an array.
Editted with new knowledge of the employee class...
Also, you will need to build the array in your main function before you pass it. Something like this:
public static void main(String[] args){
Employee [] employeeList = {
new Employee("Samuel T. Anders", "Player, Caprica Buccaneers"),
new Employee("William Adama", "Commander, Battlestar Galactica")
};
Company hungryBear = new Company("hungryBear ", "Those weird apartments ", employeeList);
}
Not really sure this answers your question, but maybe this will help you with the syntax of array passing a little.
Another edit, another way to initialize an array:
Empolyee [] employeeList = new Employee[2];
employeeList[0] = new Employee("Samuel T. Anders", "Player, Caprica Buccaneers");
employeeList[1] = new Employee("William Adama", "Commander, Battlestar Galactica");

Empolyee [] employeeList = new Employee[2];
for(int i=0;i<2;i++){
Scanner input = new Scanner(System.in);
employeeList[i] = input.next();
}

Related

NullPointerException when using .size() in an Arraylist class

currently, I'm doing an assignment that deals with the ArrayList class.
at some point, I need to check of the id of the instructor and make sure that the instructor is not added twice to the ArrayList, so I made a for loop to go through all the id that has been registered and get the id and check if it exists already
the problem is when I use the method " .size()" in the loop, the JVM throws NullPointerException
and I don't know why.
==========================================================================
what I need to read is this:
\\name - id - dateOfBirth - gender - degree - speciality - city - availability
Amanda Smith, 102020, 320101200000, M, PhD, Software Engineering, NewYork, true
=======================================================================
this is the code:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) { //ERROR OCCURE
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The problem is membersList doesn't exist when you call .size() on it
instead of
ArrayList<UniversityMember> membersList;
you need to initialize it
ArrayList<UniversityMember> membersList = new ArrayList<UniversityMember>();
You need to initialize the ArrayList.
Like that ArrayList membersList = new ArrayList();
After that, in the first size() returns 0 and not null. Remember all data structure must be initialize in java.
You haven't added anything to the membersList then asking for the size for something that has nothing in it.
Example of whats going on
String str;
for(int i = 0; i < str.length(); i++){
System.out.println("hey");
}
also you need to declare the array list like this
ArrayList<Method name> membersList = new ArrayList<Method name>();
also don't forget to import the ArrayList class
import java.util.ArrayList;
nvm I figured out that I haven't initialized my array ( ╥ω╥ )
I'll keep the question for others to be carefull
==================================================
The code after fixing it:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
/* ===== FIXING THE ERROR ======*/
membersList = new ArrayList();
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) {
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main

Java: Using .txt files to assign specific indexes of each line to an arraylist

My .txt file is
code1,description1,price1
code2,description2,price2
etc.
Using:
ArrayList<String> items = new ArrayList<String>();
String description;
File fn = new File("file.txt");
String[] astring = new String[4];
try{
Scanner readFile = new Scanner(fn);
Scanner as = new Scanner(System.in);
while (readFile.hasNext()){
astring = readFile.nextLine().split(",");
String code = astring[0];
items.add(code);
description = astring[1];
}
}catch(FileNotFoundException){
//
}
for(String things: items){
System.out.println("The code is: " + things + "The description is " + description);
}
My output prints out
code1 description1
code2 description1
code3 description1
I'm trying to figure out how to make the description update as the code's do. e.g.
code1 description1
code2 description2
code3 description3
If this question has been asked already, I apologize. I couldn't find out how to do it by searching around but if there's a reference to figure this out I'll close this down and go there. Thanks in advance!
The problem is with your logic. You are storing only astring[0] to the items ArrayList and overwriting the value of description each time. As a result on last value read is stored in description which you are printing in the loop.
I prefer creating a custom class as follows. (Just for the sake of demo otherwise you would declare your fields as private and provide getters and setters)
class MyObject {
public String code;
public String description;
public String price;
}
now instead of creating ArrayList of Strings you will create ArrayList of MyObject as follows
ArrayList<MyObject> items = new ArrayList<MyObject>();
now create a new instance of MyObject each time you read a line , populate its fields with the values from astring as follows
ArrayList<MyObject> items = new ArrayList<MyObject>();
File fn = new File("test.txt");
String[] astring = new String[4];
try {
Scanner readFile = new Scanner(fn);
Scanner as = new Scanner(System.in);
MyObject myObject;
while (readFile.hasNext()) {
astring = readFile.nextLine().split(",");
myObject = new MyObject();
myObject.code = astring[0];
myObject.description = astring[1];
myObject.price = astring[2];
items.add(myObject);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
and then finally print it using the same foreach loop as follows
for (MyObject item : items) {
System.out.println("The code is: " + item.code + " The description is: " + item.description + " The price is: " + item.price);
}
Output
The code is: code1 The description is: description1 The price is: price1
The code is: code2 The description is: description2 The price is: price2
The reason you're seeing that output is that you are not saving description along with the code inside the list, that is why the last description is saved within the description variable not all description values.
To solve this problem, you can create a simple Java Bean/POJO class
and wrap your data inside it and then you can simply fetch the value
you have saved it and then show it properly. Take a look at the code
below:
public class Launcher{
public static void main(String[] args) {
ArrayList<Item> items = new ArrayList<Item>();
File fn = new File("file.txt");
try {
Scanner readFile = new Scanner(fn);
while (readFile.hasNext()) {
String[] astring = readFile.nextLine().split(",");
String code = astring[0];
String description = astring[1];
String price = astring[2];
Item item = new Item(code, description, price);
items.add(item);
}
} catch (FileNotFoundException d) { // }
}
for (Item thing : items) {
System.out.println(String.format("The code is: %s\tThe description is: %s\tThe Price is %s",thing.getCode(),thing.getDescription(), thing.getPrice()));
}
}
}
class Item {
private String code;
private String description;
private String price;
public Item(String code, String description, String price) {
this.code = code;
this.description = description;
this.price = price;
}
public String getCode() {
return code;
}
public String getDescription() {
return description;
}
public String getPrice() {
return price;
}
}

Implementing 2 Java Classes

I'm learning java and trying to implement two java classes.
Student: firstName, lastName, departmentIn, yearGraduation, an array of UAClass this student is taking, an array of integers corresponding to the grades received for these classes
UAClass: teacherFirstName, teacherLastName, semesterOffered, numCredits
In the Student class, implement a method that calculates GPA. In the Student’s main() method, initiate one Student object and print out her GPA.
In my student.java class I have:
import java.util.*;
public class Student {
private String firstName;
private String lastName;
private String departmentIn;
private String yearGraduation;
private float [] grade;
private int counter = 0;
private String Student;
public Student(String my_firstName, String my_lastName, String my_deptIn, String my_yearGrad) {
firstName = my_firstName;
lastName = my_lastName;
departmentIn = my_deptIn;
yearGraduation = my_yearGrad;
grade = new float[5];
}
public String toString(){
String value;
value = "First Name: " + firstName + "\n";
value += "Last Name : " + lastName + "\n";
value += "Department: " + departmentIn + "\n";
value += "Grad. Year: " + yearGraduation + "\n";
return value;
}
public static void main(String[] args) {
Student my1 = new Student("Bob", "Hope", "MBA", "2018");
Student my2 = new Student("John", "Smith", "MBA", "2020");
Student my3 = new Student("Jane", "Doe", "MBA", "2021");
UAClass cy1 = new UAClass[4];
String[] secondArray = cy1.getarrayClass();
System.out.println(my1);
System.out.println(my2);
System.out.println(my3);
System.out.println(Arrays.toString(cy1));
}
}
And in my UAClass.java class I have:
import java.util.*;
public class UAClass {
private String teacherFirstName;
private String teacherLastName;
private String semesterOffered;
private String numCredits;
private String[] arrayClass = {"MBA 501","MBA 505","MBA 513","MBA 545"};
public UAClass(String teacherF, String teacherL, String semesterO, String numC) {
teacherFirstName = teacherF;
teacherLastName = teacherL;
semesterOffered = semesterO;
numCredits = numC;
}
public String[] getarrayClass(){
return arrayClass.clone();
}
}
What I am trying to do is to create an Array in 'UAClass' and having it printed into 'Student' but I can't seem to get it working.
I've modified the code as Amit suggested. When I run it, I get this error.
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: Array.getarrayClass at Homework2.Student.main(Student.java:66)
It seems to be having an issue with String[] secondArray = cy1.getarrayClass();
I took out the line String[] secondArray = cy1.getarrayClass() and it seems to run fine but now all I get is [null, null, null, null]
First of all, your UAClass has one constructor that takes String teacherF, String teacherL, String semesterO, String numC as parameters.
So you need to call this constructor like this:
UAClass cy1 = new UAClass("Teacher F", "Teacher L", "Semester", "NumC");
Secondly, you use an String[] type. This is a low-level array type. You can do this in Java, but normally people rather use a List type, and then not the raw type, but better like List<String>. List is actually an interface, but you can reference it as the Arrays class returns an implementation of the List class.
You should then use:
private List<String> arrayClass = Arrays.asList("MBA 501","MBA 505","MBA 513","MBA 545");
And you return a clone of the array. I presume you do this because you don't want the array to be changed. I would just return a concatenated String with values. Here is a nice example with a stream.
public String getClasses() {
return arrayClass.stream().collect(Collectors.joining(","));
}
Now in the Student class you can just print the list of classes like this:
System.out.println(cy1.getClasses());
When you change your code like that it will work but I couldn't understand what you are trying to do in your code.
UAClass cy1 = new UAClass("Bob", "", "", "");
String[] secondArray = cy1.getarrayClass();
System.out.println(my1);
System.out.println(my2);
System.out.println(my3);
System.out.println(cy1.getarrayClass());

Map array to object

I have an array defined as follows:
String [] source = {"26", "Tom", "foo", ...};
And a Person class:
public class Person{
private String age;
private String name;
private String print;
private String ......;//the same type and order and number of source
public Person() {
}
//full construtors
public Person(String age, String name, String print,String ....) {
this.age = age;
this.name = name;
this.print = print;
//....
}
/* setters & getters */
}
How can I map these values to a Personinstance?
this is my real coding
public static List<BasicalVo> readObject(String path) throws IOException, NoSuchMethodException {
InputStreamReader fReader = new InputStreamReader(new FileInputStream(path),"gb2312");
BufferedReader bufferedReader = new BufferedReader(fReader);
String currentLine;
String[] temp;
List<BasicalVo> basicalVoList= new ArrayList<BasicalVo>();
while ((currentLine = bufferedReader.readLine()) != null) {
temp = currentLine.split(",");//I get the Array
for (int i = 0; i < temp.length; i++) {
//I don't know hot to translate to BasicalVo .
BasicalVo vo = new BasicalVo();
basicalVoList.add(vo);
}
}
return basicalVoList;
}
If the source just contains one person's data then you can do this:
Person p = new Person(source[0], source[1], source[2] ...);
If the array is too short an ArrayIndexOutOfBoundsException will be thrown.
I.
If the array contains only one Person you only need to create the instance like this :
String[] source = new String[]{"26", "tom", "xx", "....."};
Person p = new Person(source[0], source[1], source[2], source[3],...);
Because you'll know how many parameters there is in the constructor and so you won't have an ArrayIndexOutOfBoundsException if the array is well-build
II.
Assuming you have only 3 attributes, you'll be able to do like this if the array is like this :
String[] source = new String[]{"26", "tom", "xx", "22", "john", "yy"};
ArrayList<Person> list = new ArrayList<>()
for (int i = 0; i < source.length; i += 3) {
list.add(new Person(source[i], source[i + 1], source[i + 2]));
}
III.
If you have multiple fields, you would better do like this :
public Person(String[]source) {
this.age = source[0];
this.name = source[1];
this.print = source[2];
//....
}
Because it wouldn't not surcharge the code you have in your loop which read from the data, and make it easier to do your stuff, and in fact this is not hard, because in every case if you have like 20 fields, you'll have to assignate these 20 attributs
IV.
Or last proposition with a factory method :
public static Person createPersoneFromArray(String[] array) {
Person p = new Person();
p.setAge(array[0]);
p.setName(array[1]);
//...
return p;
}
And in the main method :
Person p = Person.createPersoneFromArray(source);
you can also add another constructor to your BasicalVo class which takes a String[] as input :
public BasicalVo(String [] input) {
this.age = input[0];
this.name = input[1];
this.print = input[2];
//....
}
which you then can call in your main as follows without additional for loop
....
temp = currentLine.split(",");
BasicalVo vo = new BasicalVo(temp);
basicalVoList.add(vo);
....
You can use OpenCSV
CSVReader csvReader = new CSVReader(new FileReader("people.csv"),',');
ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
mappingStrategy.setType(Person.class);
String[] columns = new String[]{"age","name","print"};
mappingStrategy.setColumnMapping(columns);
CsvToBean ctb = new CsvToBean();
List personList = ctb.parse(mappingStrategy, csvReader);
In this specific case I think that your best option is to use reflection. Reflection are a set of classes and interfaces that allow you to call different methods at execution time. For instance:
String [] source = { "26", "tom", "xx", ... };
Constructor constructor = Person.class.getConstructors()[0]
constructor.newInstance(source)
Take into account that this example only works because you have only one constructor, and so Person.class.getConstructors()[0] returns the constructor you want. YOu can try to get the specific constructor with Person.class.getConstructors(Class<?>...), in that case you would need to pass as a parameter an array with the type of the arguments.

Java HashMap, One key multiple Values, One map

As the question reads.... and I do NOT want to use multiple maps, just one map.
My goal is to get a list of the names I enter in the input.
I have tried like a hundred different for-loops, but I always tend to end up with a list of the whole map and/or that the duplicate key is overridden.
import java.util.*;
public class Another {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name;
HashMap<String, ToA>wordkey = new HashMap<String, ToA>();
ToA a = new ToA("Doolin", "Bill", "18580824-1464");
ToA b = new ToA("Dalton", "Bob", "18701005-2232");
ToA c = new ToA("James", "Jesse", "18470905-2401");
ToA d = new ToA("Dalton", "Emmet", "18710713-0818");
wordkey.put("Doolin", a);
wordkey.put("Dalton", b);
wordkey.put("James", c);
wordkey.put("Dalton", d);
System.out.println("Efternamn:");
name = scan.next();
}
}
public class ToA{
private String fname, lname, dob;
public ToA(String fname, String lname, String dob){
this.fname = fname;
this.lname = lname;
this.dob = dob;
}
public String getFname(){
return fname;
}
public String getLname(){
return lname;
}
public String getDob(){
return dob;
}
public String toString(){
return "\nFirstname: " + fname + "\nSurname: " + lname + "\nDateOfBirth: " + dob;
}
}
For inputting Dalton, I would like the output
Firstname: Bill
Surname: Dalton
DateOfBirth: 18701005-2232
Firstname: Emmet
Surname: Dalton
DateOfBirth: 18710713-0818
I'm really stuck with this so any help is highly appreciated, Thanks
To post my comment as an answer: use a Map<String, List<ToA>> like this:
Map<String, List<ToA>> wordkey = new HashMap<>();
ToA a = new ToA("Doolin", "Bill", "18580824-1464");
ToA b = new ToA("Dalton", "Bob", "18701005-2232");
ToA c = new ToA("James", "Jesse", "18470905-2401");
ToA d = new ToA("Dalton", "Emmet", "18710713-0818");
wordkey.put("Doolin", Arrays.asList(a));
wordkey.put("James", Arrays.asList(c));
wordkey.put("Dalton", Arrays.asList(b, d));
To print the names based on the input, you can do something like this:
System.out.println("Efternamn:");
name = scan.next();
List<ToA> toas = wordkey.get(name);
if (toas != null) {
System.out.println("ToAs");
for (ToA toa : toas) {
System.out.println("ToA: " + toa);
}
}
else {
System.out.println("No ToAs found for input: " + name);
}
There are several possibilities for what you are trying to achieve. A simple one would be to use Guavas Multimap or to use Apaches MultiMap.
Another possibility is to "wrap" the Map in a class and keep a List<ToA> as Value of the Map. You'd override the put, remove and get methods to what you need

Categories

Resources