I have an ArrayList of String named "info" and each string holds the information about an instance of my class Student.
I try converting the Arraylist into an array and then parsing it using split method.
String[] Stringinfo = new String[info.size()];
Stringinfo = info.toArray(Stringinfo);
after I parse each line I try to make a new object in my for loop and adding it to the Students ArrayList. What happens is that every time I create this new object Student, the other objects which were added to Students ArrayList before, are all changed to this new object.
String[] temp;
for(int i = 1; i < LineCount + 1 ; i++)
{
temp = Stringinfo[i].split(" ");
Student s = new Student(Integer.parseInt(temp[0]), Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), Integer.parseInt(temp[4]));
Students.add(s);
}
I tried printing Students in different points and everthing is alright until the new object is created.
At any time all the objects have the same attribute values as the last object created.
this is the Student class constructor:
public Student(int certif, int class_id, int ave, int i, int a)
{
certification_num = certif;
class_id = class;
average_point = ave;
student_id = i;
age = a;
}
I searched a lot but couldn't find an answer. Sorry if the answer is obvious I am new to Java.
Any help would be appreciated.
Thanks in advance.
Edit:
public class Student{
public Student(){}
public Student(int certif, int class, int ave, int i, int a)
{
certification_num = certif;
class_id = class;
average_point = ave;
student_id = i;
age = a;
}
public static int get_certification_num(){
return certification_num;
}
public static int get_class_id(){
return class_id;
}
public static int get_average_point(){
return average_point;
}
public static int get_id(){
return student_id;
}
public static int get_age(){
return age;
}
private static int certification_num;
private static int class_id;
private static int age;
private static int node_id;
private static int student_id;
}
Take the word static out of your Student class.
static means "one of these for all Students". But every student should have a different age, id etc., so those fields (and associated methods) should not be static.
Static members means that the member belong to the class and not to the object and thus your members keeps on changing.
My guess is your members are static, so try to define your Student class like this:
public class Student {
private int certification_num;
private int class_id;
private int average_point;
private int student_id;
private int age;
public Student(int certif, int clazz, int ave, int i, int a)
{
this.certification_num = certif;
this.class_id = clazz;
this.average_point = ave;
this.student_id = i;
this.age = a;
}
}
First of all I advice you to change your Student class as follow:
public class Student
{
private int certification_num;
private int class_id;
private int average_point;
private int student_id;
private int age;
public int getCertification_num() {
return this.certification_num;
}
// Do this for all variables
public void setCertification_num(int certif) {
this.certification_num = certif;
}
// Do this for all variables
}
After that you can easy use your Student class. Also in other situations, when you don't have or need all information.
Fill your Array:
ArrayList<Student> students = new ArrayList<Student>();
for(int i = 1; i < LineCount + 1 ; i++)
{
String[] temp;
temp = Stringinfo[i].split(" ");
Student s = new Student();
s.setCertification_num(Integer.parseInt(temp[0]);
//Do for all other fields
Students.add(s);
}
Related
I dont get what i did wrong for this constructor:
public class Student(String first_name, String last_name, int home1, int home2,int quiz1, int quiz2, int quiz3, int exam1, int exam2)
{
fname=first_name;
lname=last_name;
hw1_grade=home1;
hw2_grade=home2;
quiz1_grade=quiz1;
quiz2_grade=quiz2;
quiz3_grade=quiz3;
exam1_grade=exam1;
exam2_grade=exam2;
}
The compiler says: '{' expected.
Also: < Identifier > expected it says this error over and over
public class Student {
private String fname;
private String lname;
private int hw1_grade;
private int hw2_grade;
private int quiz1_grade;
private int quiz2_grade;
private int quiz3_grade;
private int exam1_grade;
private int exam2_grade;
public Student(String first_name, String last_name, int home1, int home2, int quiz1, int quiz2, int quiz3,
int exam1, int exam2) {
fname = first_name;
lname = last_name;
hw1_grade = home1;
hw2_grade = home2;
quiz1_grade = quiz1;
quiz2_grade = quiz2;
quiz3_grade = quiz3;
exam1_grade = exam1;
exam2_grade = exam2;
}
}
Constructors are declared inside the class definition. So you define the call first, and then inside the class definition, you implement your constructor:
public class Student {
//fields
String fname;
String lname;
//... etc.
//here you declare your constructor, like so:
public Student(String first_name, String last_name, int home1, int home2,int quiz1, int quiz2, int quiz3, int exam1, int exam2)
{
fname=first_name;
lname=last_name;
hw1_grade=home1;
hw2_grade=home2;
quiz1_grade=quiz1;
quiz2_grade=quiz2;
quiz3_grade=quiz3;
exam1_grade=exam1;
exam2_grade=exam2;
}
}
Also, on a side note, these are way too many parameters for a constructor in my opinion. Why not include only the most essential ones (first name, last name, etc.) and then set exam grades using setter methods?
If you are trying to declare a class, use:
public class student{
//statements;
}
else if you are trying to declare a constructor of the class then:
public class student{
//Parameterized Constructor
public student(//parameters){
//body
}
}
Create gets and sets methods:
getStudentName() and setstudentName()
getStudentNumber() and setStudentNumber()
I am confused on what to put in the public void printGrades() and printAverage()
import java.util.Scanner;
public class studentGrader
{
Scanner input = new Scanner(System.in);
private String studentName;
private String studentNumber;
private String[] testNames;
private int[] testGrades;
private int currentTestPointer;
private int maxTestCount = 10;
private int averageGrade;
private int testScore;
public studentGrader(String studentNameL,String studentNumberL)
{
studentName = studentNameL;
studentNumber = studentNumberL;
testNames = new String[maxTestCount];
testGrades = new int[maxTestCount];
currentTestPointer = 0;
averageGrade = 0;
}
public void addTest(String testName, int testScore)
{
testNames[currentTestPointer] = testName;
}
public void printGrades()
{
}
public void printAverage()
{
}
}
//Most Getters are very simple.
//The goal is to simply return some variable that is privately stored in a class
//Notice that the variable "studentName" is of type "String" and the method is returning a type "String"
public String getStudentName() {
return studentName;
}
//Most Setters are the same as getters, except they set the variable instead
//This method takes in a parameter(in this case "name") and then sets the desired variable to given parameter
public void setstudentName(String name) {
studentName = name;
}
The getStudentNumber and setStudentNumber are the same and I'll leave that left undone as a mental exercise.
//This is an example of how to print something
public void printAverage() {
//There may be additional logic in here to determine the correct average grade
system.out.print(averageGrade);
}
There are some rules from Java code style (that not flow to error, but they are used by everyone) along with some JVM defaults:
Class name should be in camel-case: class studentGrader - class StudentGrader
Scanner class is used to work with inbound data (console, files, ets); this is not a data holder. Should be removed from the class and used as local variable in method.
In constructor (usually), same name for local properties and method parameters should be used. To get access to the local properties, do use this: this.studentName = studentName
Arrays testNames and testGrades are objects with know size. So you should declare it in the class definition and make it final (reference is final, but not array's content): private final String[] testNames = new String[10]; and private final int[] testGrades = new int[10];
Class local parameters are initialized to the default values. For int it is a 0. So no need to do it in the constructor for currentTestPointer and averageGrade
void addTest(String testName, int testScore), in your current increment currentTestPointer and check for arrays out of bound (not more than 10) (I think, it is better to use Map)
averageGrade should be double (I think): private double averageGrade;``
Finally, your class could look like this:
public class StudentGrader {
private static final int MAX_TEST_AMOUNT = 10;
private String studentName;
private String studentNumber;
private final String[] testNames = new String[MAX_TEST_AMOUNT];
private final int[] testGrades = new int[MAX_TEST_AMOUNT];
private int currentTestPointer;
private double averageGrade;
private int testScore;
public StudentGrader(String studentName, String studentNumber) {
this.studentName = studentName;
this.studentNumber = studentNumber;
}
public void addTest(String testName, int testScore) {
if (currentTestPointer < MAX_TEST_AMOUNT) {
testNames[currentTestPointer] = testName;
testGrades[currentTestPointer] = testScore;
currentTestPointer++;
}
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
public void printGrades() {
// <testName>: <testGrade>
for (int i = 0; i < currentTestPointer; i++)
System.out.println(testNames[i] + ": " + testGrades[i]);
}
public void printAverage() {
averageGrade = 0;
if (currentTestPointer > 0) {
for (int i = 0; i < currentTestPointer; i++)
averageGrade += testGrades[i];
averageGrade /= currentTestPointer;
}
System.out.println(averageGrade);
}
}
I'm having trouble with this requirement. I have this snippet:
private String id;
private int age;
private static int index;
public Customer(int a) {
this.id = a + "C" + index;
index++;
this.age = a;
}
It works fine. But the thing is, I want for every age the index will be reset to 1, like <10C1, 10C2> when there are 2 10-year-old customers and if you create a new customer with the age of 20 it will go back to <20C1,20C2,..>. Since there are no restriction to the age so the if statement seems not possible.
Use a static map in user:
private String id;
private int age;
private static map indexMap = new HashMap();
public Customer(int a) {
this.id = a + "C" + index;
index++;
this.age = a;
}
public synchronized static int getIndexOfAge(int age) {
if (!indexMap.contains(age)) {
indexMap.put(age, 1);
}
int theIndex = indexMap.get(age);
theIndex++;
indexMap.put(age, theIndex);
}
But I have to say this is really not a good way to code. You should use something like UserIndexFactory to create user index. You should also consider the thread safe and performance.
I am trying to create a unique property code every time I create new instance of the House class. For example, when I create the third house in my program, I need it to assign the integer '3' to it so that I can reference the house with that unique code. I have attempted this with a global static variable and while retaining the correct amount of objects created, it only ever returns the last instance's value.
private static int houseNo = 0;
private int propertyCode;
public House(String s, Town t, Person o){
owner = o;
street = s;
town = t;
houseNo++;
propertyCode = houseNo;
}
public String toString(){
String temp = "";
temp = "Code: " + this.getPropCode() + " \nAddress:\n" + this.getStreet() + ", " + town.getTownName();
return temp;
}
Say I have created 6 houses in my main class, using the toString to access any house will only return 6 in place of the getPropCode().
Any ideas?
Edit(More code):
public int getPropCode(){
return propertyCode;
}
And from my main class:
public static void main(String[] args) {
House house1 = new House("blueberry", town1, fred);
House house2 = new House("blackberry", town2, barney);
House house3 = new House("redberry", town3, fred);
int whichHouse = Integer.parseInt(JOptionPane.showInputDialog("Select a house to create a lease for \n1. " + house1.toString() + "\n2. " + house2.toString() + "\n3. " + house3.toString()));
Please forgive my naming convention, just trying to mess around with this code.
are you expecting like this, updated attribute for simplicity
public class Test {
private static int count = 0;
public static void main( String [] args) {
House h1 = new House("blueberry", "town1", "fred");
System.out.println(h1.toString());
House h2 = new House("blackberry", "town2", "barney");
System.out.println(h2.toString());
House h3 =new House("redberry", "town3", "john");;
System.out.println(h3.toString());
}
}
class House {
String name;
String person;
String town;
private int propertyCode;
static int count = 0;
public House(String name,String town,String person){
count = count +1;
this.propertyCode = count;
this.town = town;
this.person = person;
this.name = name;
}
public String toString(){
String temp = "";
temp = "Code: " + this.name + " " + this.propertyCode;
return temp;
}
}
Your code is not thread safe, so you should consider using AtomicInteger
private static AtomicInteger houseNo = new AtomicInteger(0);
public House(String s, Town t, Person o){
owner = o;
street = s;
town = t;
propertyCode = houseNo.incrementAndGet();
}
Specifically, it's these two lines where multiple threads running through the constructor could give you unexpected results
...
houseNo++;
propertyCode = houseNo;
...
Of course, AtomicInteger will only supply unique propertyCodes within a single JVM, but maybe that's all you need.
This works fine, so check again your code, and specially your "getPropCode"
public class House{
private static int houseNo = 0;
private int propertyCode;
public House(){
houseNo++;
propertyCode = houseNo;
}
public int getPropCode(){
return propertyCode;
}
public String toString(){
return "code: "+getPropCode();
}
}
public class Test {
public static void main(String[] args){
House a = new House();
House b = new House();
House c = new House();
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
I would like to know how to use multiples clas in Java. I know how use method from other class and also constructors but i would like know how create a new "object" for example. If i am making a PersonDirectory, then i can have class called Person which has the attributes Name and Age. Then i want to make a Person[] in my PersonDirectory Class and add names and ages to it. How can i do that? I have some code that i did, but it doesn't seem to work out.
import java.io.*;
public class PersonDirectory {
static BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
static Person[] personArray = new Person[2];
public static void main(String[] args) throws IOException{
for (int i = 0; i < personArray.length; i++) {
System.out.print("Please enter the name of the person: ");
String name = br.readLine();
System.out.print("Please enter the age of the person: ");
int age = Integer.parseInt(br.readLine());
personArray[i] = new Person(name,age);
}
for(Person p : personArray) {
System.out.println("The name is "+p.getName()+" and the age is "+p.getAge());
}
}
}
second class
public class Person {
private static String name = "";
private static int age = 0;
public Person(String name,int age) {
this.name = name;
this.age = age;
}
public static String getName() {
return name;
}
public static int getAge() {
return age;
}
}
This is because the properties in the Person class are static. Static means that they are shared between all object(instances). Remove the static keyword from the Person class and you will be fine.