I need to create an object array and read the values of the elements in the constructor from console. I am totally confused how to do it.Can anyone give a clarity about how to do it
public class Student {
int id;
String name;
double marks;
public Student(int id, String name, double marks) {
id = this.id;
name = this.name;
marks = this.marks;
}
}
public class Solution {
public static void main(String[],args)
{
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
Student[] arr=new Student[n];
for(int i=0;i<n;i++)
{
int x =sc.nextInt();
String y=sc.nextLine();
double z=sc.nextDouble();
arr[i]=arr.Student(x,y,z);
}
}
}
I am confused on how to call the constructor.
Can anyone help me?
You can do one of two things:
1.Create a temporary object by calling the constructor and then adding that object in the array:
Student temp= new Student(x,y,z);
arr[i]=temp;
2.Directly instantiate a new object and add it in the array like this:
arr[i]=new Student(x,y,z);
Both methods will work fine, but it is recommended to use method 2 because you should not allocate memory to a temp object when clearly you can achieve the goals without doing so
Instead of:
arr[i]=arr.Student(x,y,z);
Do:
arr[i]=new Student(x,y,z);
Why? Because, Each object in the array is an instance of Student class
Your constructor is declared wrongly. this is always used to refer to the instance variable. Change your constructor to this:
public class Student {
int id;
String name;
double marks;
public Student(int id, String name, double marks) {
this.id = id;
this.name = name;
this.marks = marks;
} }
public class Solution {
public static void main(String[],args)
{
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
Student[] arr=new Student[n];
for(int i=0;i<n;i++)
{
int x =sc.nextInt();
String y=sc.nextLine();
double z=sc.nextDouble();
arr[i]= new Student(x,y,z); //no need to create an object for arr
}
}
}
Because your constructor is wrong.
public class Student {
int id;
String name;
double marks;
public Student(int id, String name, double marks) {
this.id = id;
this.name = name;
this.marks = marks;
}
}
Related
import java.util.Scanner;
public class test{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
SE220Std [] stdDB=new SE220Std[2];
for(int i=0;i<stdDB.length;i++){
System.out.println("enter student's "+(i+1)+" name,id and gpa respectivly");
String n=input.next();
int d=input.nextInt();
double g=input.nextDouble();
stdDB[i]=new SE220Std (n,d,g);
}
for(int i=0;i<stdDB.length;i++){
System.out.println("student "+(i+1)+" info:- \n"+stdDB[i].getName()+"\n"+stdDB[i].getID()+"\n"+stdDB[i].getGPA());
System.out.println("-----------------");
}
for(int i=0;i<stdDB.length;i++){
if(stdDB[0].getGPA()<stdDB[i].getGPA()){
stdDB[0].getGPA()=stdDB[i].getGPA();
}
System.out.println(stdDB[0]);
}
}
}
class SEstd{
private String name;
private int id;
private double gpa;
SEstd () {
name=null;
id=0;
gpa=0;
}
public SEstd(String newName,int newID,double newGPA){
name=newName;
id=newID;
gpa=newGPA;
}
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
public int getID() {
return id;
}
public void setID(int newID) {
this.id = newID;
}
public double getGPA() {
return gpa;
}
public void setGPA(double newGPA) {
this.gpa = newGPA;
}
}
error: The left-hand side of an assignment must be a variable
so I am trying to create a data base for students that saves their name ,id number and gpa in one object then save each object in an array. I wanted to add feature which is displaying the highest gpa but I had an error while testing and I didn't know how to change my code
how can I compare the gpa above from each student to save the highest one ?
I tried using multiple ways but nothing seemed right
You can't assign to the return of a getter like that. That's what setters are for:
stdDB[0].setGPA(stdDB[i].getGPA());
I have a program I am working with to help me practice my coding skills. The program has the following scenario: there is a classroom of 20 students, where the record is taken of the students' names, surnames, and age. Half of these students take part in the school's athletics. Here, record is kept of their races that they have done and the ones they've won.
In this program, I have three classes:
runStudents - class with main method
Students (String name, String surname, int age) - parental class
AthleticStudents (String name, String surname, int age, int races, int victories) - sub class
The user should be able to add another race (and win) to the object. As seen by the code provided, an Array is created to store the 20 Students objects. I have to be able to access a method to alter the object in the array, but this method is not in the parental class (the class the objects are created from.
public class Students
{
private String name;
private String surname;
private int age;
public Students()
{
}
public Students(String name, String surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName()
{
return this.name;
}
public String getSurname()
{
return this.surname;
}
public double getAge()
{
return this.age;
}
public void setName(String name)
{
this.name = name;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return String.format("name\t\t: %s\nsurname\t\t: %s\nage\t\t: %s",
this.name, this.surname, this.age);
}
}
public class AthleticStudents extends Students
{
private int races;
private int victories;
public AthleticStudents()
{
}
public AthleticStudents(String name, String surname, int age, int
races, int victories)
{
super(name, surname, age);
this.races = races;
this.victories = victories;
}
public int getRaces()
{
return this.races;
}
public int getVictories()
{
return this.victories;
}
public void setRaces(int races)
{
this.races = races;
}
public void setVictories(int victories)
{
this.victories = victories;
}
public void anotherRace()
{
this.races = this.races + 1;
}
public void anotherWin()
{
this.victories = this.victories + 1;
}
public String toString()
{
return super.toString() + String.format("\nnumber of races\t:
%s\nnumber of wins\t: %s", this.races, this.victories);
}
}
public class runStudents
{
public static void main(String[]args)
{
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
}
}
I want to be able to do the following:
AthleticStudents[1].anotherRace();
but cannot do so as the array object is derived from the parental class, and I declared the method in the sub class. How can I link the two?
I assume that you create an array of the parent class instances. Just cast the instance this way (you better check whether the element is the instance of a subclass):
if (AthleticStudents[1] instanceof AthleticStudents)
((AthleticStudents) AthleticStudents[1]).anotherRace();
I'm not sure if this is exactly what you're looking for but it worked well for me. Instead of trying to access AthleticStudents method anotherRace() like that, try this in your main method.
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
AthleticStudents addRace= (AthleticStudents)myStudents[1];
addRace.anotherRace(); //This will increment Eva's race count to 4
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
All I did was cast the element into an object AthleticStudents named 'addRace'. By casting myStudents[1] to this new object you are able to access all of AthleticStudents methods.
I just saw the other answer posted which works just as well!
Hope this helps!
I’m not sure that i understand your question, because you are a bit inconsistent with your capitalization. runStudents is a class, while AthleticStudents is both a class and an array. But i’ll try.
IF i did understand your question, you have an array Student[] studentArray. Some Student objects in studentArray are AthleticStudents, others are not. You have a specific AthleticStudent eva which is in studentArray[] having let’s say index 1, and you want to add to her anotherRace(). Your call studentArray[1].anotherRace does not compile because the compiler treats that element as a Student and not as a AthleticStudent.
The trick is to cast the element to AthleticStudent. I omit the test of the element of being really an AthleticStudent; you will have to do that test in your code.
((AthleticStudent) studentArray[1]).anotherRace();
I am using a copy constructor and Inheritance in a class called 'Department' to call the information from class 'Teacher' which is a sub-class of 'Person'. After creating my set/get methods, I get the above error. Anyone have any insight as to why this is occurring?
Code from 'Department' class:
public class Department {
private String deptName;
private int numMajors;
private Teacher[] listTeachers; //inherits from Person class
private Student[] listStudents; //inherits from Person class
// First constructor for Department
public Department(String dn, int nm, Teacher[] listTeachers, Student[] listStudents) {
this.deptName = dn;
this.numMajors = nm;
this.listTeachers = new Teacher[listTeachers.length];
for (int i = 0; i < this.listTeachers.length; i++)
{
this.listTeachers[i] = new Teacher (listTeachers[i]);
}
//set method for Teachers Array
public void setListTeachers (Teacher[] other) {
this.listTeachers = new Teacher[other.length];
for (int i = 0; i < listTeachers.length; i++) {
this.listTeachers[i] = new Teacher (other[i]);
}
}
//get method for Teachers Array
public Teacher[] getListTeachers() {
Teacher[] copyTeachers = new Teacher[listTeachers.length];
for (int i = 0; i < copyTeachers.length; i++) {
copyTeachers[i] = new Teacher(this.listTeachers[i]);
}
return copyTeachers;
}
Here are the lines giving me errors:
1) this.listTeachers[i] = new Teacher (listTeachers[i]);
2) this.listTeachers[i] = new Teacher (other[i]);
3) copyTeachers[i] = new Teacher(this.listTeachers[i]);
Code from 'Teacher' class:
public class Teacher extends Person {
private String id;
private int salary;
private int num_yr_prof;
//Constructor for use in Teacher main method.
public Teacher(String n, int a, String s, boolean al, String i, int sal, int numyr) {
super(n, a, s, al);
this.id = i;
this.salary = sal;
this.num_yr_prof = numyr;
}
//Copy constructor for use in Department class.
public Teacher (String n, int a, String s, boolean al, Teacher other) {
super(n, a, s, al);
if (other == null) {
System.out.println("Fatal Error!");
System.exit(0);
}
this.id = other.id;
this.salary = other.salary;
this.num_yr_prof = other.num_yr_prof;
}
Your copy constructor might look like this:
public Teacher(Teacher teacher) {
this( teacher.n, teacher.a, teacher.s, teacher.al,
teacher.id, teacher.salary, teacher.num_yr_prof );
}
Since you do not show the code for the Person class, I have used the variable names n, a, s, and al here. They should be replaced by whatever those variables are named in the Person class. This, of course, assumes that those variables are either public or protected. If they are private, you need to use the getters for those variables (preferred even if they are public or protected).
You need to to your Teacher class a constructor that accepts a Teacher:
public Teacher(Teacher teacher) {
// do something
}
I'm new to JAVA and I struggled with this question which is very unclear to me. I'm politely asking if someone could discussing it with me or teach me how to answer it? Thank you.
Question:
A Company class holds an array of employees and its constructor takes in as parameters 4 arrays of the same length. The first array is an array of String being the names of employees; the second array is an array of String being the respective addresses; the third array is an array of int being the respective employee numbers; the fourth array is an array of double being the respective salaries.
I know how to do the public constructor one but I am unsure about the constructor of the class Company.
Your help is very valuable to me. Thank you in advance.
Feels like a very simple class structure.
public class Company {
Employee[] employees;
public Company (String[] names, String[] addresses, int[] ids, double[] salaries) {
employees = new Employee[names.length];
for (int i = 0; i < employee.length; i++) {
employees[i] = new Employee (names[i], addresses[i], ids[i], salaries[i]);
}
}
static class Employee {
String name;
String address;
int id;
double salary;
Employee (String name, String address, int id, double salary) {
this.name = name;
this.address = address;
this.id = id;
this.salary = salary;
}
}
}
Please delete question if this is a school assignment and you are using stackoverflow to cheat.
public Company(String[] names, String[] addresses, int[] employeeNumbers, double[] salaries) {
}
A better design would be
public Company(Employee[] employees) {
}
and have an employee class
public class Employee {
private String name;
private String address;
private int employeeNumber;
private double salary; // you may not want to use this in production
public Employee(String name, String address, int employeeNumber, double salary) {
}
// constructors, getters and setters, etc
}
According to #Kayaman comment seems you already have an employee class but for some reason you don't want to use the first constructor that takes an array of employees instead of 4 arrays. You want to use the first constructor with the 4 array parameters and construct array objects from the parameters. That's actually bad programming. It makes you code look dirty.
If it's a school assignment and you are required to do it that way, I'm guessing the instructor probably just wants you to learn something out of it. But code like that should not be written in production.
Anyways, here is the solution you might be looking for
public class Company {
private Employee[] employees;
public Company(String[] names, String[] addresses, int[] employeeNumbers, double[] salaries) {
employees = new Employees[names.length]; // assuming all arrays are of the same length
for (int i = 0;i < employees.length;i++) {
employees[i] = new Employee(names[i], addresses[i], employeeNumbers[i], salaries[i]);
}
}
}
import java.util.ArrayList;
import java.util.Collections;
public Class Company
{
ArrayList<Employee> employees = new ArrayList<Employee>();
public Company(Employee[] newEmployees)
{
employees.addAll(newEmployees);
}
}
public Class Employee
{
public String Name;
public String Address;
public Int Id;
public Double Salary;
public Employee(string name, string address, int id, double salary)
{
this.Name = name;
this.Address = address;
this.Salary = salary;
this.Id = id;
}
}
To create a new company:
Employee[] e = {
new Employee("Bob", "Bobs address", 1, 50000),
new Employee("Jane", "Janes address", 3, 85000)
}
Company c = new Company(e);
i was trying to make a program that asks the user to create a person or a group of persons and assign names and age to them. So I made a constructor "Try" and a method "AskUser".in AskUser() I use a do/while loop where user is asked to input a name, an age and if he likes to create another person. Now how do I take the input data each time the loop runs, and send it to constructor to create new objects with it? And how these new objects will be called?
import java.util.Scanner;
public class Try{
static String name;
static int age;
static Scanner a = new Scanner(System.in);
static Scanner b = new Scanner(System.in);
static Scanner c = new Scanner(System.in);
public Try(String name, int age){
this.name=name;
this.age= age;
System.out.println("this is "+name+", and he is "+age+" old.");
}
public static void AskUSer(){
int x=0;
do {System.out.print("what's the name of the person ?");
name= a.nextLine();
System.out.print("how old is he? ");
age= b.nextInt();
System.out.print("would u like to creat another person ");
String yes = c.nextLine();
if(!(yes.equals("yes"))){x++;}
} while(x==0);
}
public static void main (String[] args){
AskUSer();
System.out.print(age+ " "+ name);
}
}
You can construct the new object in AskUSer and return it as return value. So the code would look like:
public static YourObject AskUSer() {
...
}
aside from how you read from the user ,
it will be appropriate to make a class..
something like :
class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
and before entering the loop
you could use an ArrayList to hold people
ArrayList<Person> people = new ArrayList<Person>();
and each time you read the inputs .. instantiate a Person object and add it to the ArrayList
something like :
Person pr=new Person(name,age);
people.add(pr);