How can I make two instances of a class, update the same array from that class? Like here, I want r1 and r2 to update same pendingOrders, so that finally the array is ['yo', 'lo']. That is not happening, the r1 and r2 are making different arrays.
import java.util.ArrayList;
public class Student{
static int enrollmentNumber;
String studentName;
Student(String name){
enrollmentNumber += 1;
studentName = name;
}
public String toString(){
return enrollmentNumber+": "+this.studentName;
}
public static void main(String[] args) {
Student s = new Student("Pam");
System.out.println(s.toString());
Student s1 = new Student("Hellooo");
System.out.println(s1.toString());
Student s2 = new Student("Pam2");
System.out.println(s2.toString());
Robot r1 = new Robot("Bob");
r1.addToQueue("yo");
System.out.println(r1.returnList()); // prints: ['yo']
Robot r2 = new Robot("Rob");
r2.addToQueue("lo");
System.out.println(r2.returnList()); // prints: ['lo']
// But I want it to print ['yo', 'lo']
}
}
class Robot{
public ArrayList<String> pendingOrders = new ArrayList<String>();
String rName;
Robot(String name){
rName = name;
}
public void addToQueue(String s){
pendingOrders.add(s);
}
public ArrayList returnList(){
return pendingOrders;
}
}
Add the static keyword to the pendingOrders in Robot.
Check this guide for more info
Related
I have a subclass "OnlineCourse". It´s a subclass of "Course". I want to return "OnlineCourse" in my class "Student". But instead of "EIST" I get back null.
Here´s what I have:
public class Student {
public String matriculationNumber;
public String name;
public int age;
public Course study() {
TODO 4: Comment the code below back in
Change the Course type to OnlineCourse and set its
title to "EIST"
return the new course
// Course course = new Course();
// course.join();
// return course;
Course EIST = new OnlineCourse();
EIST.join();
return EIST;
}
}
Subclass that extends course and should be initiated as the return type for "EIST" in the class Student.
public class OnlineCourse extends Course{
public URL livestreamUrl;
public Course join() {
System.out.println("joined the course " + title);
return this;
}
public Course drop() {
System.out.println("dropped out of the course" + title);
return this;
}
}
public abstract class Course {
public String title;
public String description;
public LocalDate examDate;
public List<Lecture> lectures;
public abstract Course join();
public abstract Course drop();
}
Main- Method:
public class Main {
public static void main(String[] args) {
var student = new Student();
student.matriculationNumber = "01234567";
student.name = "Joe Doe";
student.age = 42;
student.study();
}
}
I think you're saying the course title is showing as null. In which case you have to set it for it to print. I'd also note that where you have EIST - that's just a variable name, it can be anything and doesn't have any affect on any values.
If I were to guess, I think you'd want something like this -
public static void main(String[] args) {
var student = new Student();
student.matriculationNumber = "01234567";
student.name = "Joe Doe";
student.age = 42;
student.study("EIST");
}
And in Course, you'd want a setter method for the title like, -
public setCourseTitle(String title) {
this.title = title;
}
And in Student
public Course study(String courseTitle) {
Course EISTCourse = new OnlineCourse();
EISTCourse.setCourseTitle(courseTitle);
EISTCourse.join();
return EISTCourse;
}
I'm new to Java. How do you add String data into an Object "myData" and print out the contents of it in main?
public class myData {
static String[] myArray = new String[] { "Mimi Rudolph", "minirudolph" };
public static String[] cutName(String string) {
return string.split(" ");
}
String[] fullName = cutName(myArray[0]);
String skype = myArray[1];
String github = null;
Object myData = new Object();
public myData(String[] fullName, String skype, String github) {
this.fullName = fullName;
this.skype = skype;
this.github = github;
}
public static void main(String[] args) {
Object myData = new Object();
}
}
#Tai, I think you're missing some concepts in your code.
Once Java is an Object Oriented Programming language, you should avoid using the static in your methods when you want to have a new instance of a class.
To call methods with static, you don't need a new instance of an object (can call it as MyData.cutName, for example.
On the other hand, constructors will be accessed when you create a new instance of your object.
I believe you can get rid of the arrays, but I kept it in your cutName method.
You could have something like this.
public class MyData {
private String fullname;
private String skype;
private String github;
public MyData(String fullname, String skype, String github) {
this.fullname = fullname;
this.skype = skype;
this.github = github;
}
public String getFullname() {
return this.fullname;
}
public String getSkype() {
return this.skype;
}
public String getGithub() {
return this.github;
}
public String[] cutName(String string) {
return string.split(" ");
}
#Override
public String toString() {
return "Fullname: " + this.fullname + "; Skype: " + this.skype + "; Github: " + this.github;
}
public static void main(String[] args) {
MyData myData = new MyData("Mimi Rudolph", "minirudolph_skype", "minirudolph_githnub");
System.out.println("First name: " + myData.cutName(myData.getFullname())[0]);
System.out.println("Last name: " + myData.cutName(myData.getFullname())[1]);
System.out.println(myData);
}
}
The output would be:
First name: Mimi
Last name: Rudolph
Fullname: Mimi Rudolph; Skype: minirudolph_skype; Github: minirudolph_githnub
Having the attributes in your class and setting it from the new instance will help you to have reusability.
Hope it helps.
I think you are looking for something like this:
public class MyData {
private static final String[] myArray = new String[]{"Mimi Rudolph", "minirudolph"};
String[] fullName = cutName(myArray[0]);
String skype = myArray[1];
String github = null;
Object myData = new Object();
private static String[] cutName(String string) {
return string.split(" ");
}
public MyData(String[] fullName, String skype, String github) {
this.fullName = fullName;
this.skype = skype;
this.github = github;
}
public static void main(String[] args) {
MyData myData = new MyData(myArray, "Skype string goes here", "githun string goes here");
System.out.println(myData.fullName);
System.out.println(myData.github);
System.out.println(myData.skype);
}
}
You need to simply create an instance of your class myData as next:
public static void main(String[] args) {
myData myData = new myData(myArray, "skype", "github");
...
}
To print its content you could override the method toString() for example like this:
#Override
public String toString() {
return "myData{" +
"fullName=" + Arrays.toString(fullName) +
", skype='" + skype + '\'' +
", github='" + github + '\'' +
", myData=" + myData +
'}';
}
Then you will be able to print its content using System.out.println(myData).
So the final code would look like this:
public class myData {
...
#Override
public String toString() {
...
}
public static void main(String[] args) {
myData myData = ...
System.out.println(myData);
}
}
Usually you can add string to object by the following simple example:
String a = "abc";
Object b = a;
System.out.println(b);
If you want to assign a complete String array to myData Object, then you need to do the following:
Object[] myData = new Object[myArray.length];
for(int i=0;i<myArray.length;i++){
myData [i] = myArray[i];
System.out.println("MyData Object Array holding strings data: "+myData[i]);
}
In you main method, you need to change object to object of Arrays first:
From - Object myData = new Object();
TO: Object[] myData = new Object[myArray.length];
I am trying to solve an assignment in my Java class. I am stuck and need a little help.
I am trying to create a method in my Group class that will display the group name and the 4 students in the group. My code currently displays the group name and the memory location of my student inside my array.
public class Group {
/**-------Declaring attributes----*/
String groupName;
int newStudentCount;
/**----------------------------*/
/**--------Constructor------------*/
public Group(String givenGroupName) {
groupName = givenGroupName;
}
Student[] students = new Student[4];
/**----------------------------*/
/**--------Method------------*/
void addStudent(Student st) {
students[newStudentCount] = st;
++newStudentCount;
System.out.println("New student: " +st.getName());
}
public String getGroup() {
return "Group = " + groupName;
}
public Student getStudent(){
return students[0];
}
}
In my App class I have this:
public class App {
public static void main(String[] args) {
Group g1 = new Group("Pink Pony Princesses");
Student st1 = new Student("Joshua Mathews");
st1.getName();
g1.addStudent(st1);
Student st2 = new Student("Jame Brooks");
g1.addStudent(st2);
Student st3 = new Student("Mike Myers");
g1.addStudent(st3);
Student st4 = new Student("Christie Richie");
g1.addStudent(st4);
System.out.println(g1.getGroup()+ " " + g1.getStudent());
}
This is my Student class:
public class Student {
/**-------Declaring attributes----*/
String name;
String degree;
int age;
/**----------------------------*/
/**--------Constructor------------*/
Student(String givenName){
name = givenName;
}
Student(String givenName, String givenDegree, int givenAge) {
name = givenName;
degree = givenDegree;
age = givenAge;
}
/**--------- METHODS --------*/
//Array
public final String [] activities = {
"Working on Homework", "Playing a Game", "Taking a Nap"
};
String getInfo(){
return name + age + degree;
}
String getName() {
return name;
}
int getAge(){
return age;
}
String getDegree() {
return degree;
}
String whatsUp(){
Random rand = new Random();
int randomIndex = rand.nextInt(activities.length);
String returnActivity = activities[randomIndex];
return returnActivity;
}
I'm not sure how to call my array to display the 4 names, and not the memory location of them. Any help would be greatly appreciated.
I can deduce a couple of things from your question.
First, you are returning only the student at index 0 of the Student array held within your Group object. If you want to return all students your method signature should have a Student[] as the return type rather than a Student object.
If you follow the above prompt then you will have to iterate through the returned array printing each Student object.
Regardless of which implementation you choose the reason you print out a memory reference rather than a String object is that you have not overridden toString within your Student class.
Something like this will print out Student data when passed to a System.out call:
#Override
public String toString() {
return someStudentData;
}
You can go with what andrewdleach said by implementing toString(). OR
To print all student names your method should be something like:
public String getStudent(){
String studentNames = "";
for(Student stu: students){
studentNames+= stu.getName() + ",";
}
return studentNames;
}
I want the out put is like this:
Conan is NOT the same age as Natsu
this output program create the latest parameters.
Natsu is the same age as Natsu.
below is java program that I have made.
Syntax code that I have made
package rawrandomtest;
public class GetSet002 {
private static String name;
private static int age;
public GetSet002(String s, int i){
GetSet002.name = s;
GetSet002.age = i;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public void setAge(int x){
GetSet002.age =x;
}
}
Driver Code
package rawrandomtest;
import java.util.Scanner;
public class GetSet002Driver {
public static Scanner input = new Scanner (System.in);
public static void main (String[] args){
GetSet002 p1 = new GetSet002("Conan", 14);
GetSet002 p2 = new GetSet002("Natsu", 18);
if(p1.getAge()==p2.getAge()){
System.out.println(p1.getName()+" is the same age as "+p2.getName());
}else{
System.out.println(p1.getName()+" is NOT the same age as "+p2.getName());
}
}
}
The age is a static variable. You change the value for all instances, every time you set the variable.
GetSet002 p1 = new GetSet002("Conan", 14);
//result: GetSet002 = ("Conan" , 14)
GetSet002 p2 = new GetSet002("Natsu", 18);
//result: GetSet = ("Natsu" , 18);
if(p1.getAge() == p2.getAge())
//is semantically equal to:
if(GetSet002.age == GetSet002.age)
//public accessiblity is only implied for demonstration
I'm a web developer dabbling in Java (again) and I'm having trouble with something.
Basically, I have a superclass Employee with two subclasses that extend it called Management and Programmer. The Employee class contains an array employees that is basically an array of Employee objects.
Here's the important snippets of two of the classes (Employee and Management) and the final main method. I'll explain the output at the bottom.
public class **Employee** {
private static String firstName;
protected static int MAXEMPLOYEES = 5;
protected Employee[] employees = new Employee[MAXEMPLOYEES];
protected int totEmployees = 0;
public Employee(String first) {
setFirstName(first);
}
public void setFirstName(String str){
firstName = str;
}
public String getFirstName(){
return firstName;
}
public boolean addEmployee(String fname) {
boolean added = false;
if (totEmployees < MAXEMPLOYEES) {
Employee empl = new Employee(fname);
employees[totEmployees] = empl;
added = true;
totEmployees++;
}
return added;
}
}
public class **Management** extends **Employee** {
private String title = "Project Manager";
public Management(String fname, String t){
super(fname);
title = t;
}
public boolean addManagement(String fname, String t){
boolean added = false;
if (totEmployees < MAXEMPLOYEES) {
employees[totEmployees] = new Management(fname, t);
added = true;
totEmployees++;
}
return added;
}
}
-------------------------------------
package employee;
public class EmployeeApplication {
public static void main(String[] args) {
Employee[] empl = new Employee[3];
empl[0] = new Employee("Kyle");
empl[1] = new Management("Sheree", "Director");
System.out.println(empl[0].getFirstName());
}
}
Now, I expect the system to print out "Kyle", but it prints out "Sheree". Any ideas???
private static String firstName;
You made firstName static, which means all instances share the same name. You'll need to remove the static modifier in order for different Employees to have different names. You'll also need to change the private access modifier to protected in order for the field to be inherited by subclasses.
private String firstName;
remove static;
Kyle was overridden by Sheree, that is why you are getting that output