how I display value of Participants who are in both events - java

Q. Create a class named Participant with fields for a name, age, and street address. Include a constructor that assigns parameter values to each field and a toString() method that returns a String containing all the values.
Also include an equals() method that determines two Participants are equal if they have the same values in all three fields.
Create an application with two arrays of at least 5 Participants each--one holds the Participants in the mini-marathon and the other holds Participants in the diving competition. Prompt the user for Participants who are in both events save the files as Participant.java and TwoEventParticipants.java.*/
Here is my code so far. How do I display the value of Participants who are in both events ?
import javax.swing.JOptionPane;
import java.util.*;
public class TwoEventParticipants {
private static Participant mini[] = new Participant[2];
private static Participant diving[] = new Participant[2];
public static void main(String[] args) {
String name="";;
String add="";
int age=0;
Participant p=new Participant(name, age, add);
Participant p1=new Participant(name, age, add);
setParticipant();
setParticipant1();
displayDetail();
displayDetail1();
//Arrays.sort(p1);
if (p.equals(p1)){
System.out.println(p);
}else{
System.out.println(p1);
}
}
public static void setParticipant(){
for (int x = 0; x < mini.length; x++) {
System.out.println("Enter loan details for customer " + (x + 1) + "...");
//Character loanType=getLoanType();
//String loanType=getLoanType();
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
mini[x] = new Participant(name, age, add); //<--- Create the object with the data you collected and put it into your array.
}
}
public static void setParticipant1(){
for (int y = 0; y < diving.length; y++) {
System.out.println("Enter loan details for customer " + (y + 1) + "...");
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
diving[y] = new Participant(name, age, add);
}
}
// Participant p=new Participant(name,age,add);
//displayDetails();
// System.out.println( p.toString());
public static void displayDetail() {
// for (int y = 0; y < diving.length; y++) {
System.out.println("Name \tAge \tAddress");
//Participant p=new Participant(name,age,add);
for (int x = 0; x < mini.length; x++) {
System.out.println(mini[x].toString());
// System.out.println(diving[y].toString());
}
}
public static void displayDetail1() {
System.out.println("Name \tAge \tAddress");
for (int y = 0; y < diving.length; y++) {
System.out.println(diving[y].toString());
}
}
public static String getName() {
Scanner sc = new Scanner(System.in);
String name;
System.out.print(" Participant name: ");
return name = sc.next();
}
// System.out.print(" Participant name: ");
// name = sc.next();
public static int getAge() {
int age;
System.out.print(" Enter age ");
Scanner sc=new Scanner(System.in);;
return age= sc.nextInt();
}
public static String getAdd() {
String add;
Scanner sc=new Scanner(System.in);;
System.out.print("Enter Address: ");
return add=sc.next();
}
}
Participant with fields for a name, age, and street address
//
public class Participant {
private String name;
private int age;
private String address;
public Participant(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
#Override
public String toString() {
return name + " " + age + " " + address ;
}
// include an equals() method that determines two Participants are equal
public boolean equals(Participant[] name,Participant[] age,Participant[] add) {
if (this.name.equals(name) && this.address.equals(address)&& age == age){
return true;
}
else{
return false;
}
}
}

This will work for you:
for(Participant p : mini){
if(diving.contain(p)){
System.out.pringtln(p.toString()) ;
}
}

Related

Why does the method only return 0 ? (Java) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
The idea of this program is to calculate the person's weight and age on each planet. and Life class is supposed to be the one who do the calculations and return the values correctly.
my problem is when i run the program it returns 0 ! but I want it to do the calculations and return different values.
Person Class
package solarsystemplanets;
public class Person {
private String name;
public int age;
public double weight;
//Constructors
public Person(String n, int a, double w) {
n = name;
a = age;
w = weight;
}
public Person(){
name = "";
age = 0;
weight = 0;
}
//Setters (Mutator)
public void setName(String n) {
n = name;
}
//Getters (Accessor)
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getWeight() {
return weight;
}
//PrintDetails Method
public String toString() {
return "Person" + " name=" + name + ", age=" + age + ", weight="
+ weight;
}
}
Life Class
package solarsystemplanets;
public class Life extends Person {
private int earthDays;
public double []surfaceGravity;
public int []planetsDays;
//Constructors
public Life (int e, double []s, int []p){
earthDays = e;
surfaceGravity = s;
planetsDays = p;
}
public Life (int ee){
earthDays = 365;
surfaceGravity = new double[]{0.38,0.91,1.0,0.38,2.34,0.93,0.92,1.12};
planetsDays = new int[]{88,225,365,2,12,29,84,165};
}
public Life(){
this.surfaceGravity = new double[]{0.38,0.91,1.0,0.38,2.34,0.93,0.92,1.12};
this.planetsDays = new int[]{88,225,365,2,12,29,84,165};
}
//Setters (Mutator)
public void setEarthDays(int e) {
earthDays = e;
}
//Getters (Accessor)
public int getEarthDays() {
return earthDays;
}
public double[] getSurfaceGravity() {
double array1[] = new double[surfaceGravity.length];
for(int i =0; i < surfaceGravity.length; i++){
array1[i] = weight * surfaceGravity[i];
}
return array1;
}
public int[] getPlanetsDays() {
int array2[] = new int[planetsDays.length];
for(int i =0; i < planetsDays.length; i++){
array2[i] = (age * getEarthDays())/ planetsDays[i];
}
return array2;
}
//PrintDetails Method
public String toString(int i) {
return "surfaceGravity=" + getSurfaceGravity() + ", planetsDays=" + getPlanetsDays();
}
}
Main
package solarsystemplanets;
import java.util.*;
import java.io.*;
public class SolarSystemPlanets {
public static void main(String[] args) throws IOException {
Person person = new Person();
Life life = new Life();
Planet planet = new Planet();
Scanner input = new Scanner (System.in);
File file = new File ("Solar System Planets");
//User Info
System.out.println("What is Your Name ? ");
person.setName(input.nextLine());
System.out.println("Please Enter Your Age: ");
person.age = input.nextInt();
while (person.age <=0){
System.out.println("error. Please Enter Your Age Again: ");
person.age = input.nextInt();
}
System.out.println("Please Enter Your Weight: ");
person.weight = input.nextInt();
while (person.weight <=0){
System.out.println("error. Please Enter Your Weight Again: ");
person.weight = input.nextInt();
}
for(int i =0; i<planet.planetName.length; i++){
System.out.println(planet.planetName[i]);
System.out.println("Your Weight = " + life.getSurfaceGravity()[i] + "
Your Age = " + life.getPlanetsDays()[i]);
}
}
}
You are setting user inputs on person object and using life object to calculate and print data. As these objects are different fields in life object remains zero.
Life extends Person, so it has inherited person fields. Set all user inputs on life object.
Also, you've forgot to set earthDays on life object.

Trouble getting input for object array

I am trying to create a class that receives data about a person's name, exam subject, and exam score. I have these classes so far:
APExam:
public class APExam {
//instance variables
private String mySubject;
private int myScore;
//constructors
public APExam(String subject, int score) {
mySubject = subject;
myScore = score;
}
public APExam() {
mySubject = "";
myScore = 1;
}
//getters and setters
public void setSubject(String s) {
mySubject = s;
}
public String getSubject() {
return mySubject;
}
public void setScore(int score) {
myScore = score;
}
public int getScore() {
return myScore;
}
//compareTo
public String compareTo(int s) {
if(myScore == s)
return "Scores are equal.";
else if(myScore > s)
return "The first score is greater than the second score.";
else
return "The second score is greater than the first score.";
}
//equals
public boolean equals(String str) {
return mySubject.equals(str);
}
//toString
public String toString() {
return "Subject: " + mySubject + "\nScore: " + myScore;
}
}
APStudent:
public class APStudent {
//instance variables
private String myFirstName;
private String myLastName;
private ArrayList<APExam> myExams = new ArrayList<APExam>();
//constructors
public APStudent(String fname, String lname) {
myFirstName = fname;
myLastName = lname;
}
public APStudent() {
myFirstName = "";
myLastName = "";
}
//getters and setters
public void setFirstName(String fname) {
myFirstName = fname;
}
public String getFirstName() {
return myFirstName;
}
public void setLastName(String lname) {
myLastName = lname;
}
public String getLastName() {
return myLastName;
}
public ArrayList<APExam> getExams() {
return myExams;
}
//addExam
public void addExam(APExam ex) {
myExams.add(ex);
}
//computeExamAverage
public double computeExamAverage(List<APExam> exams) {
int sum = 0;
for(int i = 0; i < exams.size(); i++) {
sum += exams.get(i).getScore();
}
return (double) sum / exams.size();
}
//findHighestExamScore
public int findHighestExamScore(List<APExam> exams) {
int max = exams.get(0).getScore();
for(APExam ex : exams) {
if(ex.getScore() > max) {
max = ex.getScore();
}
}
return max;
}
//numberOfFives
public int numberOfFives(List<APExam> exams) {
int fiveCount = 0;
for(APExam ex : exams) {
if(ex.getScore() == 5) {
fiveCount++;
}
}
return fiveCount;
}
}
ArrayListTest:
public class ArrayListTest {
public static void main(String[] args) {
//instance variables
final String QUIT = "end";
Scanner sc = new Scanner(System.in);
ArrayList<APExam> myExams = new ArrayList<APExam>();
APStudent student = new APStudent();
String fname, lname, sub, input = "";
int score;
//prompt for info
System.out.print("Enter first name: ");
fname = sc.nextLine();
student.setFirstName(fname);
System.out.print("\nEnter last name: ");
lname = sc.nextLine();
student.setLastName(lname);
while(!input.equals(QUIT)) {
APExam ap = new APExam();
System.out.print("\nEnter exam subject or 'end' to quit: ");
input = sc.nextLine();
sub = input;
ap.setSubject(sub);
System.out.print("\nEnter exam score: ");
score = sc.nextInt();
ap.setScore(score);
student.addExam(ap);
sc.nextLine();
}
//display information
System.out.println(student.getExams());
System.out.println("Name: " + student.getFirstName() + " " + student.getLastName());
System.out.println("Exam average score: " + student.computeExamAverage(myExams));
System.out.println("Highest score: " + student.findHighestExamScore(myExams));
System.out.println("Number of fives: " + student.numberOfFives(myExams));
System.out.println();
for(int i = 0; i < myExams.size(); i++) {
System.out.println(myExams.get(i));
}
//prompt for search
System.out.println("1 sequential search"
+ "\n2 binary search"
+ "\n3 exit");
input = sc.nextLine();
while(!((input.equals("1") || input.equals("2") || input.equals("3")))) {
switch(input) {
case "1":
sequentialSearch(myExams, 3);
break;
case "2":
binarySearch(myExams, 2);
break;
case "3":
break;
}
}
}
}
For some reason in the ArrayListTest class it doesn't create an APExam object with the inputted scores and subjects. Is there something wrong with the while loop? Or is something else wrong?
Your problem is that you are for some reason passing variable List<APExam> exams into your functions. When you are doing that you are passing a empty ArrayList<APExam> and that's why it throws a IndexOutOfBoundsException.
You shouldn't pass anything and just use the APStudent's myExams list.
public double computeExamAverage() {
double sum = 0;
for (APExam myExam : myExams) {
sum += myExam.getScore();
}
return sum / myExams.size();
}
public int findHighestExamScore() {
int max = 0;
for(APExam exam : myExams) {
if(exam.getScore() > max) max = exam.getScore();
}
return max;
}
public int numberOfFives() {
return (int) myExams.stream().filter(apExam -> apExam.getScore() == 5).count();
}
EDIT: I would like to comment on your main method too. You should use the parametrized constructors instead of default one and setters. And you should check on the input being "end" before you ask for grade.
public static void main(String[] args) {
final String QUIT = "end"; // not really necessary, but ok
Scanner sc = new Scanner(System.in);
String firstName, lastName, subject;
int score;
//prompt for info
System.out.print("Enter first name: ");
firstName = sc.nextLine();
System.out.print("\nEnter last name: ");
lastName = sc.nextLine();
APStudent student = new APStudent(firstName, lastName); // use of parametrized constructor
while(true) {
System.out.print("\nEnter exam subject or 'end' to quit: ");
subject = sc.nextLine();
if (subject.equals(QUIT)) break; // check if user wants to end it
System.out.print("\nEnter exam score: ");
score = sc.nextInt();
student.addExam(new APExam(subject, score)); // use of parametrized constructor
sc.nextLine();
}
sc.close(); // never forget to close Scanner
//display information etc.
}

storing arraylist, phonebookdemo program(Need two more lines)?

I need to fill in the blanks on a phone book entry and phone book demo class. I've filled them all in except for two of them in the demo class, the parts that I need to fill in are represented by question marks.
PhoneBookEntry:
public class PhoneBookEntry
{
private String name; // Person's name
private String phoneNumber; // Person's phone number
/**
* The constructor initializes the person's name
* and phone number.
*/
public PhoneBookEntry(String n, String pn)
{
name = n;
phoneNumber = pn;
}
/**
* The setName method sets the person's name.
*/
public void setName(String n)
{
name = n;
}
/**
* setPhoneNumber method sets the person's
* phone number.
*/
public void setPhoneNumber(String pn)
{
phoneNumber = pn;
}
/**
* The getName method returns the person's
* name.
*/
public String getName()
{
return name;
}
/**
* The getPhoneNumber method returns the
* person's phone number.
*/
public String getPhoneNumber()
{
return phoneNumber;
}
}
I filled in the blanks on that one, in the PhoneBookDemo I don't have a clue on what to put in the spaces with the question marks:
public class PhoneBookDemo
{
public static void main(String args[])
{
// Constant for the numer of entries.
final int NUM_ENTRIES = 5;
// Create an ArrayList to hold PhoneBookEntry objects.
ArrayList<PhoneBookEntry> list =
new ArrayList<PhoneBookEntry>();
// Tell the user what's about to happen.
System.out.println("I'm going to ask you to enter " +
NUM_ENTRIES + " names and phone numbers.");
System.out.println();
// Create and store PhoneBookEntry objects in the ArrayList.
for (int i = 0; i < NUM_ENTRIES; i++)
{
???????
System.out.println();
}
System.out.println("Here's the data you entered:");
// Display the data stored in the ArrayList.
for (int i = 0; i < list.size(); i++)
{
????????????
}
}
/**
* The getEntry method creates a PhoneBookEntry object
* populated with data entered by the user and returns
* a reference to the object.
*/
public static PhoneBookEntry createEntry()
{
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Variables to hold a person's name and
// phone number.
String name;
String phoneNumber;
// Get the data.
System.out.print("Enter a person's name: ");
name = keyboard.nextLine();
System.out.print("Enter that person's phone number: ");
phoneNumber = keyboard.nextLine();
// Create a PhoneBookEntry object.
PhoneBookEntry entry = new PhoneBookEntry(name, phoneNumber);
// Return a reference to the object.
return entry;
}
/**
* The displayEntry method displays the data stored
* in a PhoneBookEntry object.
*/
public static void displayEntry(PhoneBookEntry entry)
{
System.out.println("------------------------------");
System.out.println("Name: " + entry.getName());
System.out.println("Phone number: " + entry.getPhoneNumber());
}
}
You can use the two methods in your code which are not used
// Create and store PhoneBookEntry objects in the ArrayList.
for (int i = 0; i < NUM_ENTRIES; i++)
{
list.add (createEntry());
}
and
for (int i = 0; i < list.size(); i++)
{
displayEntry(list.get(i));
}
Create and store : call the method that create an instance, and add it to the list
for (int i = 0; i < NUM_ENTRIES; i++){
PhoneBookEntry create = createEntry();
list.add(create);
System.out.println();
}
Display : call the displayEntry method on each element, but the best way is to implement the toString() method in the PhoneBookEntry class and use a System.out.println(list.get(i));
for (int i = 0; i < list.size(); i++){
displayEntry(list.get(i));
}
Take a look at following code:
public class PhoneBookDemo {
public static void main(String args[]) {
// Constant for the numer of entries.
final int NUM_ENTRIES = 5;
// Create an ArrayList to hold PhoneBookEntry objects.
ArrayList<PhoneBookEntry> list
= new ArrayList<PhoneBookEntry>();
// Tell the user what's about to happen.
System.out.println("I'm going to ask you to enter "
+ NUM_ENTRIES + " names and phone numbers.");
System.out.println();
// Create and store PhoneBookEntry objects in the ArrayList.
for (int i = 0; i < NUM_ENTRIES; i++) {
list.add(createEntry());
}
System.out.println("Here's the data you entered:");
// Display the data stored in the ArrayList.
for (int i = 0; i < list.size(); i++) {
displayEntry(list.get(i));
}
}
/**
* The getEntry method creates a PhoneBookEntry object populated with data
* entered by the user and returns a reference to the object.
*/
public static PhoneBookEntry createEntry() {
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Variables to hold a person's name and
// phone number.
String name;
String phoneNumber;
// Get the data.
System.out.print("Enter a person's name: ");
name = keyboard.nextLine();
System.out.print("Enter that person's phone number: ");
phoneNumber = keyboard.nextLine();
// Create a PhoneBookEntry object.
PhoneBookEntry entry = new PhoneBookEntry(name, phoneNumber);
// Return a reference to the object.
return entry;
}
/**
* The displayEntry method displays the data stored in a PhoneBookEntry
* object.
*/
public static void displayEntry(PhoneBookEntry entry) {
System.out.println("------------------------------");
System.out.println("Name: " + entry.getName());
System.out.println("Phone number: " + entry.getPhoneNumber());
}
}
public class PhoneBookEntry {
private String name;
private String phoneNumber;
public PhoneBookEntry() {
}
public PhoneBookEntry(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the phoneNumber
*/
public String getPhoneNumber() {
return phoneNumber;
}
/**
* #param phoneNumber the phoneNumber to set
*/
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
I think you should not hold phone book's entires apart from phone bool. Do incapsulate this logic into the phone book:
public final class PhoneBook {
private final Map<String, Entry> entries = new TreeMap<>();
public void add(String name, String phoneNumber) {
entries.put(name, new Entry(name, phoneNumber));
}
public Iterator<Entry> iterator() {
return entries.values().iterator();
}
public static final class Entry {
private final String name;
private final String phoneNumber;
public Entry(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
}
}
Then you can define method, that ask user for phone book entries and retrieves the whole phone book instead of list of phone book's entreis:
public static PhoneBook getPhoneBook(int totalEntries) {
try (Scanner scan = new Scanner(System.in)) {
PhoneBook phoneBook = new PhoneBook();
System.out.println("I'm going to ask you to enter " + totalEntries + " names and phone numbers.");
System.out.println();
for (int i = 1; i <= totalEntries; i++) {
System.out.println("Entry " + i + ':');
System.out.print("Enter a person's name: ");
String name = scan.nextLine();
System.out.print("Enter that person's phone number: ");
String phoneNumber = scan.nextLine();
System.out.println();
phoneBook.add(name, phoneNumber);
}
return phoneBook;
}
}
Finally you can use this method to get a phone book and print all entires:
final int totalEntries = 5;
getPhoneBook(totalEntries).iterator().forEachRemaining(entry -> {
System.out.println("------------------------------");
System.out.println("Name: " + entry.getName());
System.out.println("Phone number: " + entry.getPhoneNumber());
});
//iterate over number of entries
for (int i = 0; i < NUM_ENTRIES; i++)
{
//add to the phonebooklist
list.add (createEntry());
System.out.println();
}
System.out.println("Here's the data you entered:");
// Display the data stored in the ArrayList.
for (int i = 0; i < list.size(); i++)
{
//display entry from list
displayEntry(list.get(i));
//use display entry method for display
}

I have some issue with my output

The Cullerton Part District holds a mini-Olympics each summer. Create a class named Participant with fields for a name, age, and street address. Include a constructor that assigns parameter values to each field and a toString() method that returns a String containing all the values. Also include an equals() method that determines two Participants are equal if they have the same values in all three fields. Create an application with two arrays of at least 5 Participants each--one holds the Participants in the mini-marathon and the other holds Participants in the diving competition. Prompt the user for Participants who are in both events save the files as BC.java and ABC.java.
import javax.swing.JOptionPane;
import java.util.*;
public class ABC {
private static Participant mini[] = new Participant[2];
public static void main(String[] args) {
setParticipant();
displayDetail();
}
// BC p=new BC(name,age,add);
//displayDetails();
// System.out.println( p.toString());
public static void displayDetail() {
String name=null;
String add = null;
int age=0;
System.out.println("Name\tAdress\tAge");
BC p=new BC(name,age,add);
for (int x = 0; x < mini.length; x++) {
//Participant p1=mini[x];
System.out.println(p.toString());
}
}
public static String getName() {
Scanner sc = new Scanner(System.in);
String name;
System.out.print(" Participant name: ");
return name = sc.next();
}
// System.out.print(" Participant name: ");
// name = sc.next();
public static int getAge() {
int age;
System.out.print(" Enter age ");
Scanner sc=new Scanner(System.in);;
return age= sc.nextInt();
}
public static String getAdd() {
String add;
Scanner sc=new Scanner(System.in);;
System.out.print("Enter Address: ");
return add=sc.next();
}
public static void setParticipant(){
for (int x = 0; x < mini.length; x++) {
System.out.println("Enter loan details for customer " + (x + 1) + "...");
//Character loanType=getLoanType();
//String loanType=getLoanType();
String name=getName();
String add=getAdd();
int age=getAge();
System.out.println();
}
}
}
//another class
public class BC {
private String name;
private int age;
private String address;
public BC(String strName, int intAge, String strAddress) {
name = strName;
age = intAge;
address = strAddress;
}
#Override
public String toString() {
return "Participant [name=" + name + ", age=" + age + ", address=" + address + "]";
}
public boolean equals(Participant value){
boolean result;
if (name.equals(name) && age==value.age && address.equals(address))
result=true;
else
result=false;
return result;
}
}
outPut:
Enter loan details for customer 1...
Participant name: hddgg
Enter Address: 122
Enter age 12
Enter loan details for customer 2...
Participant name: ddjkjde
Enter Address: hdhhd23
Enter age 12
//Why I'm not getting right output
Name Adress Age
Participant [name=null, age=0, address=null]
Participant [name=null, age=0, address=null]
You are getting that output because of this method:
public static void displayDetail() {
String name=null;
String add = null;
int age=0;
System.out.println("Name\tAdress\tAge");
BC p=new BC(name,age,add);
for (int x = 0; x < mini.length; x++) {
//Participant p1=mini[x];
System.out.println(p.toString());
}
}
You are creating a BC with null for name and add and 0 for age. You are then printing it twice.

Having trouble printing my array of objects

I am trying to write an application that takes in a user specified number, then makes that many objects (I am calling them Students) assigns a random name and number to them then sorts their numbers. I have the sorts worked out but am having issues with printing the array. My code is below. The output that I am getting is "New Object" the number of times I enter, followed by "0: null" for each of me toString calls. Any help would be greatly appreciated. Thank you.
import java.util.Random;
import java.util.Scanner;
public class application {
public static void main(String[] args) {
int studentSerialNumber;
String studentName;
System.out.println("Enter the number of students you would like to sort: ");
Scanner scanner = new Scanner(System.in);
int numOfStudents = scanner.nextInt();
Student[] anArrayToSort = new Student[numOfStudents];
for (int i = 0; i < anArrayToSort.length; i++) {
studentSerialNumber = ((int)(Math.random() * 8888)) + 1000;
studentName = getStudentName();
anArrayToSort[i] = new Student(studentSerialNumber, studentName);
}
for (int i = 0; i < anArrayToSort.length; i++) {
System.out.println(anArrayToSort[i].toString());
}
}
private static String getStudentName() {
String studentName = "";
int i = 7;
Random r = new Random();
while (i > 0) {
char c = (char) (r.nextInt(26) + 'a');
studentName = studentName + c;
i--;
}
return studentName;
}
}
public class Student {
int studentSerialNumber;
String studentName;
Student(int studentSerialNumber, String studentName) {
studentSerialNumber = studentSerialNumber;
studentName = studentName;
System.out.println("New Object");
}
public String toString() {
return studentSerialNumber + ": " + studentName;
}
}
Assignments in constructor are bad:
Student(int studentSerialNumber, String studentName) {
studentSerialNumber = studentSerialNumber;
studentName = studentName;
System.out.println("New Object");
}
this should be:
Student(int studentSerialNumber, String studentName) {
this.studentSerialNumber = studentSerialNumber;
this.studentName = studentName;
System.out.println("New Object");
}
Currently you're assigning values to themselves and not to Student instance fields.

Categories

Resources