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

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
}

Related

Cannot get names to display from an array using getName

I am currently using java and still haven't got the hang of everything so bear with me. I have been trying to get my names to appear on the output menu but I must be missing something in my code.
Here is my code it has a driver class and client class:
import java.util.Scanner;
//This is TestBaby.java class
public class TestBaby {
// This is main() method, program execution start from here
public static void main(String[] args) {
// This is Scanner class object, it will help to take value from end user
Scanner scan = new Scanner(System.in);
//This is array object of Baby type
Baby[] babies = new Baby[4];
//This is for loop, it iterates 4 times for holding 4 Babies data
for(int i=0; i<4; i++) {
//a. Enter details for each baby (name and age) and thus populate the Baby array
System.out.println("Enter details of " + "Baby " +(i+1));
if(i!=0)
scan.nextLine();
System.out.println("Enter name: ");
String name = scan.nextLine();
System.out.println("Enter age: ");
int age = scan.nextInt();
//This is Baby class object*/
Baby baby = new Baby();
//Set name in Baby class object whatever user entered
baby.setName(name);
//Set age in Baby class object whatever user entered
baby.setAge(age);
//Store current Baby class object into babies array
babies[i] = baby;
}//for end
//b. Output the details of each baby from the array (name and age)
int i=0;
for(Baby baby : babies) {
System.out.println("Baby name: " + baby.getName());
System.out.println("Baby age: " + baby.getAge());
i++;
}
//c. Calculate and display the average age of all babies in the array
double averageAge = averageAge(babies);
System.out.println("Average age of all babies: "+averageAge);
//d. Determine whether any two babies in the array are the same
for(i=0; i<babies.length; i++) {
for(int j=i+1; j<babies.length; j++) {
System.out.println(babies[i].getName()+ " and " + babies[j].getName() + " are equal? " + babies[i].equals(babies[j]));
}//inner for loop
}//outer for loop
}//main() end
//This is averageAge() method, it will calculate average age of Babies
public static double averageAge(Baby[] babies) {
//These are local variables of averageAge() method
int size = babies.length;
double averageAge = 0.0;
//This is for loop, it will calculate total age of babies
for(int i=0; i<size; i++) {
averageAge = averageAge + babies[i].getAge();
}//for end
//return average age to caller of this method
return averageAge/size;
}//averageAge() end
}// TestBaby end
//This is Baby.java class
public class Baby {
//These are instance variable of Baby.java class
private String name;
private int age;
//This is default constructor
public Baby() {
name = "Baby";
age = 1;
}
//This is parameterized constructor will take two parameters, a string to set the name and an integer to set the age
public Baby(String name, int age) {
this.name = name;
this.age = age;
}
//Supply methods for setting the name, setting the age, getting the name and getting the age.
public String getName() {
return name;
}
public void setName(String name) {
//The set method for the name instance variable should ensure that the input is not empty or contain whitespaces (otherwise set a default value)
if (name.trim().isEmpty()){
this.name = "Baby";
this.name = name;
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
//The set method for the age instance variable should validate the input to be between 1 and 4 inclusive (otherwise set a default value).
if (age >= 1 && age <= 4) {
this.age = age;
} //if end
else {
this.age = 1;
}//else end
}// setAge() end
//Give Java code for an equals method for the Baby class.
#Override
public boolean equals(Object obj) {
//This is type casting
Baby baby = (Baby)obj;
//Compare name and age of Baby, if both are same then return true otherwise return false
if(this.age == baby.age && this.name.equalsIgnoreCase(baby.name))
return true;
return false;
}//equals() end
}// Baby end
Please try the code first so you understand what I mean incase its not clear
Baby.setName(String name) only sets the name if name is empty. Your method:
public void setName(String name) {
if (name.trim().isEmpty()){
this.name = "Baby";
this.name = name;
}
}
Try this:
public void setName(String name)
{
if (name == null) ​
​ {
// Use default from constructor
return;
}
String n = name.trim();
if (!n.isEmpty())
​{
​this.name = n;
}
}
I guess your setName() is badly written. You only set the new name if it is empty. I guess there is a not (!) missing.

Creating an array of students based on user input

I'm trying to create an array of math students, science students, and computer students based on the user input.
So basically the user should choose what student they want to add and then enter the student details.
Below I have added the code I have so far:
Main Java class:
public class Lab4 {
public static final int DEBUG = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent(4,5);
s[1] = new MathStudent(5,7);
s[2] = new MathStudent(2,8);
s[3] = new MathStudent(3,6);
s[4] = new ScienceStudent(8,9);
s[5] = new ScienceStudent(3,6);
s[6] = new ScienceStudent(4,9);
s[7] = new ComputerStudent(6,12);
s[8] = new ComputerStudent(11,14);
s[9] = new ComputerStudent(13,17);
}
}
Student class:
public class Student {
private String name;
private int age;
public String gender = "na";
public static int instances = 0;
// Getters
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
// Setters
public void setAge(int age){
this.age = age;
}
public void setName(String name){
if (Lab4.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student(){
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
*/
public Student(int age, String name){
this.age = age;
this.name = name;
}
/**
* Gender constructor
* #param gender
*/
public Student(String gender){
this(); // Must be the first line!
this.gender = gender;
}
/**
* Destructor
* #throws Throwable
*/
protected void finalize() throws Throwable{
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString (){
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender;
}
public String getSubjects(){
return this.getSubjects();
}
}
MathStudent class:
public class MathStudent extends Student {
private float algebraGrade;
private float calculusGrade;
public MathStudent(float algebraGrade, float calculusGrade) {
this.algebraGrade = algebraGrade;
this.calculusGrade = calculusGrade;
}
public MathStudent() {
super();
algebraGrade = 6;
calculusGrade = 4;
}
// Getters
public void setAlgebraGrade(float algebraGrade){
this.algebraGrade = algebraGrade;
}
public void setCalculusGrade(float calculusGrade){
this.calculusGrade = calculusGrade;
}
// Setters
public float getAlgebraGrade() {
return this.algebraGrade;
}
public float getCalculusGrade() {
return this.calculusGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Algebra Grade: " + algebraGrade + " Calculus Grade: "
+ calculusGrade);
}
}
scienceStudent class:
public class ScienceStudent extends Student {
private float physicsGrade;
private float astronomyGrade;
/**
* Default constructor
*/
public ScienceStudent() {
super();
physicsGrade = 6;
astronomyGrade = 7;
}
public ScienceStudent(float physicsGrade, float astronomyGrade) {
this.physicsGrade = physicsGrade;
this.astronomyGrade = astronomyGrade;
}
// Getters
public void setPhysicsGrade(float physicsGrade){
this.physicsGrade = physicsGrade;
}
public void setAstronomyGrade(float astronomyGrade){
this.astronomyGrade = astronomyGrade;
}
// Setters
public float getPhysicsGrade() {
return this.physicsGrade;
}
public float getAstronomyGrade() {
return this.astronomyGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Physics Grade: " + physicsGrade + " Astronomy Grade: "
+ astronomyGrade);
}
}
computerStudent class:
public class ComputerStudent extends Student {
private float fortanGrade;
private float adaGrade;
/**
* Default constructor
*/
public ComputerStudent() {
super();
fortanGrade = 4;
adaGrade = 9;
}
public ComputerStudent(float fortanGrade, float adaGrade) {
this.fortanGrade = fortanGrade;
this.adaGrade = adaGrade;
}
// Getters
public void setFortanGrade(float fortanGrade){
this.fortanGrade = fortanGrade;
}
public void setAdaGrade(float adaGrade){
this.adaGrade = adaGrade;
}
// Setters
public float getFortanGrade() {
return this.fortanGrade;
}
public float getAdaGrade() {
return this.adaGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Fortan Grade: " + fortanGrade + " Ada Grade: " + adaGrade);
}
}
How Would I go about this?
You can ask for the number of students with type on each input and dynamically create the object.
Here is an example
System.out.println("Enter total number of students");
int n = scannerObject.nextInt();
Student students[] = new Students[n];
for(int i=0;i<n;i++){
int type = scannerObject.nextInt();
if(type == 1)
students[i] = new MathStudent();
}
Similarly, you can write for others.
For allowing user to enter his choice as input
You can do this(interpreted by your comments)
Pseudo code -
Print:
Enter 1 for math student
Enter 2 for Science student
Enter 3 for Comp student
Input choice
Now in your code use either multiple if else or better switch statement
switch(choice){
case 1: create object of math student
break;
case 2: create object of science student
break;
case 3:create object of comp student
break;
default: if not above by default do this
}
You could use an ArrayList and switch case to make your life easier. Your code should be like this:
import java.util.ArrayList;
import java.util.Scanner;
public class Students {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
switch (lesson) {
case "Math":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Algebra grade: ");
int alg = input.nextInt();
System.out.print("Give student's Calculus grade: ");
int calc = input.nextInt();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new MathStudent(alg, calc);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((MathStudent) st).getSubjects());
break;
case "Science":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Physics grade: ");
int physics = input.nextInt();
System.out.print("Give student's Astronomy grade: ");
int astronomy = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ScienceStudent(physics, astronomy);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ScienceStudent) st).getSubjects());
break;
case "Computers":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Fortran grade: ");
int fortran = input.nextInt();
System.out.print("Give student's Ada grade: ");
int ada = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ComputerStudent(fortran, ada);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ComputerStudent) st).getSubjects());
break;
default:
System.out.println("Wrong lesson");
addMore = false;
break;
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
The code above asks for the lesson name (Computers, Math, Science) and if it is one of them it reads all the info about the student and the grades for the corresponding lesson. It creates the objects and adds them in the list students. When all info is added, it asks the user if he/she wants to add another student and if he writes the letter y, then all these are made again, until the user answers something different than the letter y (the letter n in most cases). After these it prints all the students' info by itterating the list.
Note: I think in your code for the ComputerStudent class, you meant to name the variable fortranGrade and not fortanGrade (change it also in the getSubjects function).
Links:
Java ArrayList
Switch Case in Java
Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
I hope this helped you. If you have any questions or wanted something more you can do it.
UPDATE
The code below does the same things, but it uses for loop instead of switch case, as you asked in your comment.
package students;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Lab4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
ArrayList<Class<?>> studentClasses = new ArrayList<>();
studentClasses.add(MathStudent.class);
studentClasses.add(ComputerStudent.class);
studentClasses.add(ScienceStudent.class);
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
addMore = false;
for (Class studentClass : studentClasses) {
try {
st = (Student) studentClass.newInstance();
if (st.getLessonName().equals(lesson)) {
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's " + st.getSubjectsNames()[0] + " grade: ");
float firstSubj = input.nextFloat();
System.out.print("Give student's " + st.getSubjectsNames()[1] + " grade: ");
float secondSubj = input.nextFloat();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = (Student) studentClass.getConstructor(float.class, float.class).newInstance(firstSubj, secondSubj);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(st.getSubjects());
addMore = true;
break;
}
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(Lab4.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
System.out.println("Wrong lesson. Try again.");
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
You also need to add the functions in the classes as mentioned bellow:
Student class:
public String getLessonName(){
return "";
}
public String[] getSubjectsNames(){
return new String[] {"", ""};
}
MathStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Algebra", "Calculus"};
}
#Override
public String getLessonName(){
return "Math";
}
ComputerStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Fortran", "Ada"};
}
#Override
public String getLessonName(){
return "Computers";
}
ScienceStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Physics", "Astronomy"};
}
#Override
public String getLessonName(){
return "Science";
}
Changes: The code firstly creates an arraylist with the student classes (studdentClasses) and adds all the classes for the students that are currently in the project (MathStudent, ComputerStudent, ScienceStudent). Then the user adds the lesson's name. Then (instead of the switch case) there is a for loop which itterates through the studdentClasses list and checks if the lesson's name that the user has written is the same with a student's class by using the getLessonName function. After that all the info for the student are asked and the grades for the subjects, and for the question (Give student's Physics grades) it uses the function getSubjectsNames. All the other things are like before.
You have a main class, that's what you need essentially, but you need to read from command line. Great, run from command line. Once you run, pay attention to what you did, you can pass parameters there as well. once you pass parameters, they go in line. This line is logically splitable, so split it within you code. for instance by pair of numbers after some key word like science and until next keyword and put again from java and ask a new question once you there.

Java Coding Array List Trouble

I am very unexperienced with java and i need help with my school assingment. I am not sure how to get user input. The code was provided to us and we just have to put a ling of code in place of the dotted lines to complete the program but I am stuck.
I have two classes and here they are.
/**
* Write a description of class PhoneBookEntry here.
*
* #author (your name)
* #version (a version number or a date)
*/
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;
}
}
/**
* Chapter 7
* Lab Assignment: Phone Book ArrayList
* This program demonstrates the PhoneBookEntry class.
*/
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();
// 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++)
{
System.out.println(list);
}
}
/**
* The getEntry method creates a PhoneBookEntry object
* populated with data entered by the user and returns
* a reference to the object.
*/
public static PhoneBookEntry getEntry()
{
// 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());
}
}
In the loop (the dotted lines) you just need to add:
list.add(getEntry());
The handling of the stream is already implemented in getEntry() method.
Add this stuff to your code:
outside the Main class:
import java.util.Scanner;
inside the main class
Scanner input = new Scanner(System.in);
System.out.println("Asking for input");
String userResponse = input.nextLine();
For an Int rather than a string:
Int userResponse = input.nextInt();
The program will pause and wait for an input. Then, your userResponse will now contain what the user typed in.

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.

how I display value of Participants who are in both events

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()) ;
}
}

Categories

Resources