Cant change method's variables in Java objects - java

I have a problem with changing variable value in contact object. I'm trying to make a contact list but I can't change value of variables trought methods. I have editContact method which calls changeName method, both methods are passed ArrayList object trought reference so it shouldn't have problems with changing values trought ArrayList in main method, but problem is when I want to change object's name it won't change it. Is there something I'm missing here?
package telefonski_imenik;
public class Contact {
protected String name;
protected String lastname;
protected String number;
public Contact(String name, String lastname, String number) {
setName(name);
setLastName(lastname);
setNumber(number);
}
public void setName(String name) {
this.name = name;
}
public void setLastName(String lastname) {
this.lastname = lastname;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return this.name;
}
public String getLastName() {
return this.lastname;
}
public String getNumber() {
return this.number;
}
}
package telefonski_imenik;
import java.util.ArrayList;
import java.util.Scanner;
public class TelefonskiImenik {
public static void createContact(String ime, String prezime, String broj, ArrayList<Contact>
ContactList) {
Contact noviKontakt = new Contact(ime, prezime, broj);
ContactList.add(noviKontakt);
}
public static void editContact(ArrayList<Contact> ContactList) {
System.out.println("Unesite nove podatke");
changeName(ContactList);
}
public static void changeName(ArrayList<Contact> ContactList) {
Scanner novinput = new Scanner(System.in);
System.out.println("Unesite staro ime");
String oldName = novinput.nextLine();
System.out.println("Unesite novo ime");
String newName = novinput.nextLine();
for (int i = 0; i < ContactList.size(); i++) {
if (ContactList.get(i).equals(oldName)) {
ContactList.get(i).setName(newName);
}
}
novinput.close();
}
public static void main(String[] args) {
ArrayList<Contact> ContactList = new ArrayList<Contact>();
Scanner input = new Scanner(System.in);
System.out.println("Unesite podatke");
String name = input.nextLine();
String lastname = input.nextLine();
String number= input.nextLine();
createContact(name, lastname, number, ContactList);
for (int i = 0; i < ContactList.size(); i++) {
System.out.println(ContactList.get(i).getName());
System.out.println(ContactList.get(i).getLastName());
System.out.println(ContactList.get(i).getNumber());
}
editContact(ContactList);
for (int i = 0; i < ContactList.size(); i++) {
System.out.println(ContactList.get(i).getName());
System.out.println(ContactList.get(i).getLastName());
System.out.println(ContactList.get(i).getNumber());
}
input.close();
}
}

You forgot to get the name of the object in your loop:
for (int i = 0; i < ContactList.size(); i++) {
if (ContactList.get(i).equals(oldName)) {
ContactList.get(i).setName(newName);
}
}
ContactList.get(i).getName().equals(oldName)

Related

Java Isolate comma seperated values in text file

I've been searching for a solution to my problem without any luck. So now I'm asking here for help.
I'm creating "Groups" by the following class:
public class Group {
private String groupID;
private ArrayList<User> usersInGroup;
The User class looks like this:
NOTE: I already have an ArrayList containing all existing Users.
public class User {
private String firstName;
private String lastName;
private String age;
private String gender;
private String usernameID;
private String password;
I'm already adding the groupID field from the "groupData.txt" CSV text file like this:
public static ArrayList<Group> listOfCreatedGroups() throws IOException {
ArrayList<Group> listOfGroups = new ArrayList<>();
FileReader fr = new FileReader("src/groupData.txt");
BufferedReader bfr = new BufferedReader(fr);
String line;
int totalLine = Destination.linesInFile("src/groupData.txt"); //total lines in file
for (int i = 0; i < totalLine; i++) {
line = bfr.readLine();
String[] groupID = line.split(",");
Group temp = new Group();
temp.setGroupID(groupID[0]);
listOfGroups.add(temp);
}
try {
bfr.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
return listOfGroups;
}
The "groupData.txt" file is structured like this:
Line example = groupID,String_1,String2,String3 ... Stringn,\n
groupid,user,user,user,user,user,user,user,
groupid,user,user,user,
groupid,user,user,user,user,user
groupid,user,user
groupid,user,user,user,user
Since I only have the number of users in every group User.usernameID as 1 to n strings in the text file I can't add the whole User object to the Arraylist usersInGroup.
I somehow need to isolate the usernameID's and find the corresponding Users and add them to the ArrayList usersInGroup.
I hope any of you can give me a hint in the right direction. Thanks.
I don't know if this is how you were wanting because I didn't find the user data very specific or even mentioned of how you wanted. But let me know if this is enough
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class Group {
private static String groupID;
private static ArrayList<User> usersInGroup = new ArrayList<User>();
public static void main (String [] args) throws IOException {
addListToGroup(readFile());
}
public static void addListToGroup(ArrayList<ArrayList<String>> list) {
for (int i = 0; i < list.size(); i++) {
groupID = list.get(i).get(0);
for (int x = 0; x < list.get(i).size(); x++) {
User temp = new User(); // change this to however you setup the txt file
// the information from the list is in list.get(i).get(x) in order as in the textfile
temp.setAge(null);
temp.setFirstName(null);
temp.setGender(null);
temp.setLastName(null);
temp.setPassword(null);
temp.setUsernameID(null);
usersInGroup.add(temp);
}
}
}
public static ArrayList<ArrayList<String>> readFile() throws IOException {
List<String> temp = new ArrayList<String>();
Path path = Paths.get("file.txt");
temp = Files.readAllLines(path);
ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
for (int i = 0; i < temp.size(); i++) {
String [] s = temp.get(i).split(",");
ArrayList<String> quickArray = new ArrayList<String>();
for (int x=0; x < s.length; x++) {
quickArray.add(s[x]);
}
lines.add(quickArray);
}
return lines;
}
}
class User {
private String firstName;
private String lastName;
private String age;
private String gender;
private String usernameID;
private String password;
//setters and getters
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getUsernameID() {
return usernameID;
}
public void setUsernameID(String usernameID) {
this.usernameID = usernameID;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

3 separate ArrayList

ACME wants to layoff some employees. Using three ArrayLists, form three lists of employees. The first list will contain all the programmers, the second all the non-programming people making over one hundred thousand dollars, and the last all other people. Using separate loops print out the contents of each ArrayList. (The following are what I did, but not work... looking for help)
import java.util*;
class Employee
{
private String name;
private String address;
private String position;
private double salary;
private String getName()
{return name;}
public String getAddress()
{return address;}
public double getPosition()
{return position;}
public double getSalary()
{return salary;}
public void setName(String aName)
{name=aName;}
public void setAddress(String aAddress)
{address=aAddress;}
public void set(double aPosition)
{postion=aPosition;}
public void setSalary(double aSalary)
{salary=aSalary;}
public employee(String aName, String aAddress, double aPosition; double aSalary)
{
name=aName;
address=aAddress;
position=aPosition;
Salary=aSalary; }
public String toString()
{return name+address+position+salary;}
}
class employee
{public static void main(String[] args)
{Scanner in = new Scanner(System.in);
Employee[] Newemp=new Car[500];
for(int i=0, i<Newemp.length;i++)
{System.out.print(“Enter the name”);
String name=in.nextLine();
System.out.print(“Enter the address”);
String address=in.nextLine();
System.out.print(“Enter the position”);
double position=in.nextDouble();
System.out.print(“Enter the salary”);
double salary=in.nextInt() ;
in.nextLine();
Newemp[i]=new Employee(name, address, position, salary);
}
ArrayList<Employee>programmers=new ArrayList<Employee>();
ArrayList<Employee>nonprogrammers=new ArrayList<Employee>();
ArrayList<Employee>others=new ArrayList<Employee>();
for(int i=0; i<Newemp.salary; i++)
{if(Newemp[i]. getposition().equals(“programmer”))
programmers.add(Newemp[i]);
else if(Employee[i].getsalary()>100000
nonprogrammers.add(Newemp[i]);
else
others.add(Newemp[i]);
}
for(int i=0; i<programmer.();i++)
{
Employee<=programmer.get(i);
System.out.println(i);
}}}
i think this will help
for (int i = 0; i < Newemp.length; i++) {
if (Newemp[i].getPosition().equals("programmer")){
programmers.add(Newemp[i]);
System.out.println("programmers"+programmers);
}
else if (Newemp[i].getSalary()> 100000)
{
nonprogrammers.add(Newemp[i]);
System.out.println("salary 100000 thousand"+nonprogrammers);
} else{
others.add(Newemp[i]);
System.out.println("others"+others);
}
}
for (int i = 0; i < programmers.size(); i++) {
EmployeeData aa= programmers.get(i);
System.out.println("All aaray"+aa);
}
in your main()
for(int i=0; i < Newemp.salary; i++)
...
else if(Employee[i].getsalary()>100000
should be:
for(int i=0; Newemp[i] != null; i++)
...
else if([i].getsalary()>100000)
I hope you understand the concept of object, the methods & variables available with the array can not be mixed with others and vice-versa. length is a variable inside the array object which returns you the size. I would suggest instead of declaring a huge array and then iterating through it. Directly add your objects into an ArrayList as given below. I hope it helps.
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
private String name;
private String address;
private String position;
private double salary;`
public Employee(String aName, String aAddress, String aPosition,
double aSalary) {
name = aName;
address = aAddress;
position = aPosition;
salary = aSalary;
}
private String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getPosition() {
return position;
}
public double getSalary() {
return salary;
}
public void setName(String aName) {
name = aName;
}
public void setAddress(String aAddress) {
address = aAddress;
}
public void set(String aPosition) {
position = aPosition;
}
public void setSalary(double aSalary) {
salary = aSalary;
}
public String toString() {
return name + address + position + salary;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int maxSize = 500;
ArrayList<Employee> programmers = new ArrayList<Employee>();
ArrayList<Employee> nonprogrammers = new ArrayList<Employee>();
ArrayList<Employee> others = new ArrayList<Employee>();
for (int i = 0; i < maxSize; i++) {
System.out.println("Enter the name");
String name = in.nextLine();
System.out.print("Enter the address");
String address = in.nextLine();
System.out.print("Enter the position");
String position = in.nextLine();
System.out.print("Enter the salary");
double salary = in.nextInt();
in.nextLine();
Employee newEmployee = new Employee(name, address, position, salary);
if (position.equals("programmer"))
programmers.add(newEmployee);
else if (salary > 100000)
nonprogrammers.add(newEmployee);
else
others.add(newEmployee);
}
}
}

Dynamically fill in an ArrayList with objects

I have the abstract class Human, which is extendet by other two classes Student and Worker. I`m am trying to fill in two array lists. ArrayList of type Student and ArrayList of type Worker dynamically.
public abstract class Human {
private String fName = null;
private String lName = null;
public String getfName() {
return fName;
}
public Human(String fName, String lName) {
super();
this.fName = fName;
this.lName = lName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
}
public class Student extends Human {
private String grade = null;
public Student(String fName, String lName, String grade) {
super(fName, lName);
this.grade = grade;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
public class Worker extends Human {
private int weekSalary = 0;
private int workHoursPerDay = 0;
public Worker(String fName, String lName, int weekSalary, int workHoursPerDay) {
super(fName, lName);
this.weekSalary = weekSalary;
this.workHoursPerDay = workHoursPerDay;
}
public int getWorkSalary() {
return weekSalary;
}
public void setWorkSalary(int workSalary) {
this.weekSalary = workSalary;
}
public int getWorkHoursPerDay() {
return workHoursPerDay;
}
public void setWorkHoursPerDay(int workHoursPerDay) {
this.workHoursPerDay = workHoursPerDay;
}
public int moneyPerHour() {
return weekSalary / (5 * workHoursPerDay);
}
}
public class Program {
public static void main(String[] args) {
ArrayList<Student> student = new ArrayList<>();
ArrayList<Worker> worker = new ArrayList<>();
}
}
Sure, just add the students:
ArrayList<Student> students = new ArrayList<>(); // note: students
students.add(new Student("Jens", "Nenov", "A+"));
You can do almost exactly the same thing for the workers. If you want to use a loop, do the following:
for (int i=0; i<50; i++) {
students.add(new Student("Jens"+i, "Nenov", "A+"));
}
This will create a list of new students with different numbers after their names. If you want different data, though, that data needs to come from somewhere. For example, you might get the data from user input:
Scanner input = new Scanner(System.in);
for ...
System.out.println("Enter a first name:");
String firstname = input.nextLine();
...
students.add(new Student(firstname, lastname, grade));

Java - Adding 2 objects in an ArrayList

I'm pretty new to programming so I need help. I wanna add the SubjectGrades to the studentList ArrayList. But I think I'm doing the wrong way. What should I do for me to add the SubjectGrades to the ArrayList? Thanks
Here's my partial Main class.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
private static Scanner in;
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<Student>();
//ArrayList<SubjectGrades> Grades = new ArrayList<SubjectGrades>();
in = new Scanner(System.in);
String search, inSwitch1, inSwitch2;
int inp;
do {
SubjectGrades sGrade = new SubjectGrades();
Student student = new Student();
System.out.println("--------------------------------------");
System.out.println("What do you want to do?");
System.out.println("[1]Add Student");
System.out.println("[2]Find Student");
System.out.println("[3]Exit Program");
System.out.println("--------------------------------------");
inSwitch1 = in.next();
switch (inSwitch1) {
case "1":
System.out.println("Input student's Last Name:");
student.setLastName(in.next());
System.out.println("Input student's First Name:");
student.setFirstName(in.next());
System.out.println("Input student's course:");
student.setCourse(in.next());
System.out.println("Input student's birthday(mm/dd/yyyy)");
student.setBirthday(in.next());
System.out.println("Input Math grade:");
student.subjectGrade.setMathGrade(in.nextDouble());
System.out.println("Input English grade:");
student.subjectGrade.setEnglishGrade(in.nextDouble());
System.out.println("Input Filipino grade:");
student.subjectGrade.setFilipinoGrade(in.nextDouble());
System.out.println("Input Java grade:");
student.subjectGrade.setJavaGrade(in.nextDouble());
System.out.println("Input SoftEng grade:");
student.subjectGrade.setSoftEngGrade(in.nextDouble());
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
break;
//end case 1
Here is my Student Class.
package santiago;
public class Student {
private String lastName;
private String firstName;
private String course;
private String birthday;
SubjectGrades subjectGrade = new SubjectGrades();
public SubjectGrades getSubjectGrade() {
return subjectGrade;
}
public void setSubjectGrade(SubjectGrades subjectGrade) {
this.subjectGrade = subjectGrade;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
And my SubjectGrades class
package santiago;
public class SubjectGrades{
Double mathGrade, englishGrade, filipinoGrade, javaGrade, softEngGrade, weightedAverage;
public Double getMathGrade() {
return mathGrade;
}
public void setMathGrade(Double mathGrade) {
this.mathGrade = mathGrade;
}
public Double getEnglishGrade() {
return englishGrade;
}
public void setEnglishGrade(Double englishGrade) {
this.englishGrade = englishGrade;
}
public Double getFilipinoGrade() {
return filipinoGrade;
}
public void setFilipinoGrade(Double filipinoGrade) {
this.filipinoGrade = filipinoGrade;
}
public Double getJavaGrade() {
return javaGrade;
}
public void setJavaGrade(Double javaGrade) {
this.javaGrade = javaGrade;
}
public Double getSoftEngGrade() {
return softEngGrade;
}
public void setSoftEngGrade(Double softEngGrade) {
this.softEngGrade = softEngGrade;
}
public Double getWeightedAverage(){
weightedAverage = ((mathGrade + englishGrade + filipinoGrade + javaGrade + softEngGrade)*3) / 15;
return weightedAverage;
}
public String getScholarStatus(){
String status = "";
if(weightedAverage <= 1.5) {
status = "full-scholar";
} else if (weightedAverage <= 1.75){
status = "half-scholar" ;
} else {
status = "not a scholar";
}
return status;
}
}
Your mistake:
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade));
You are adding the student, then trying to add a void. The return value of setSubjectGrade is void, so nothing will be added:
Just do:
student.setSubjectGrade(sGrade);
studentList.add(student);
Where sGrade is an Object of type SubjectGrades, which was populated in the same way
student.subjectGrade.setSoftEngGrade(in.nextDouble()); was populated.
Use
ArrayList <SubjectGrades> list;
in student class instead SubjectGrades subjectGrade = new SubjectGrades();.
and generate getters and setters
Just remove this line:
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
The way you have done it, the student object already has the subjectGrade attribute with its values set.
You can access it with studentList.get(0).getSubjectGrade()

Where should i declare the field in this code in order for it to compile?

This is not supposed to be a client class. I'm just making a class for others to use. I'm using this for a Highschool. For example i have classes for the address, teacher, students, principal, roomnumber, etc..But its not compiling for some odd reason. I believe its because I'm not declaring a field but not sure.
import java.io.*;
public class HighSchool {
// Constructors
public HighSchool() { }
public HighSchool(String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects ) {
this.title = title;
this.teacher = teacher;
this.roomNumber = roomNumber;
this.period = period;
this.String[] students = students;
this.String address =a ddress;
this.String subjects = subjects;
}
public class Classcourse (String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects
private String period;) {
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getteacher() {
return teacher;
}
public void setteacher(String teacher) {
this.teacher = teacher;
}
public int getroomNumber() {
return roomNumber;
}
public void setroomNumber (int roomNumber) {
this.roomNumber = roomNumber;
}
public String getperiod() {
return getperiod();
}
public void setperiod (String period) {
this.period = period;
}
public String[] getstudents () {
return students[];
}
public void setstudents[] (String[] students
private String address;) {
this.students = students;
}
public String getaddress() {
return address;
}
public void setaddress (String address) {
this.address = address;
}
public String getsubjects() {
return subjects;
}
public void setsubjects (String subjects) {
this.subjects = subjects;
}
}
// modifier method
public void addstudents(String students) {
String[] newstudents = new String[students.length + 1];
for (int i = 0; i < students.length; i++) {
newstudents[i] = students[i];
}
newstudents[students.length] = student;
students = newstudents;
}
public boolean isInClass(String students) {
for (int i = 0; i < students.length; i++) {
if (students[i].equals(students)) {
return true;
}
}
return false;
}
// static creator method
public static HighSchool readFromInput() throws IOException {
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a HighSchool title: ");
HighSchool newHighSchool = new HighSchool(kb.readLine());
String students = null;
do {
System.out.print("Enter a student, or press Enter to finish: ");
students = kb.readLine();
if (students != null){
newHighSchool.addstudents(students);
}
} while (students != null);
return newHighSchool;
}
// Variables (Fields)
private String title;
private String[] students;
}
In addition, you wrote something that doesn't make sense from the point of view of Java Compiler:
private String period;) {
- probably remove ")".
The second thing:
Take a look on the declaration of class Classcourse.
It rather sounds wrong, although it can be an issue of this site's editor or something...
An "overall" hint - java has a very "intelligent" compiler in the most of the cases it can say what's wrong exactly with your code, so, assuming you're a newbie in Java, try to understand what compiler says to you.
Good luck!
Some things I noticed about the code:
public String getperiod() {
return getperiod();
}
This code will cause a endless loop when you call this function.
private String address;) {
this.students = students;
}
The compiler will give an error about the ";)". Change it to "()" to fix this.
Furthermore, you should really tell us more about the errors it's giving you. We can't help you if you don't give us the compiler errors.

Categories

Resources