Visual Studio Code Java: Cannot find symbol (class name)? - java

So I have a relatively simple program using two classes. When I compile the class I want to run I get an error saying cannot find symbol "Fighter" which is the name of my class that I am using the objects from. Both classes are in the same package. NOTE It works fine in NetBeans but I prefer to use VSC.
Here is my code.
Class I am running:
package project;
import java.util.ArrayList;
import java.util.Scanner;
public class Division
{
public static Scanner scanner = new Scanner(System.in);
public static void main(String args[])
{
ArrayList<Fighter> fighters = new ArrayList();
fighters.add(new Fighter("Conor McGregor", 29, "Ireland", 21, 3));
fighters.add(new Fighter("Gunnar Nelson", 28, "Iceland", 16, 3));
fighters.add(new Fighter("Stipe Miocic", 33, "USA", 17, 2));
fighters.add(new Fighter("Cody Garbrandt", 26, "USA", 11, 0));
fighters.add(new Fighter("Demetrious Johnson", 30, "USA", 27, 2));
fighters.add(new Fighter("Jose Aldo", 31, "Brazil", 26, 3));
fighters.add(new Fighter("George St Pierre", 40, "Canada", 25, 2));
fighters.add(new Fighter("Fabricio Werdum", 40, "Brazil", 22, 7));
fighters.add(new Fighter("Michael Bisping", 39, "United Kingdom", 30, 7));
displayAllFighters(fighters);
}
//Adds fighter to ArrayList
public static void addFighter(ArrayList<Fighter> fighters)
{
System.out.print("Please enter fighters name: \t");
String name = scanner.nextLine();
System.out.print("\nPlease enter fighters age: \t");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("\nPlease enter fighters country: \t");
String country = scanner.nextLine();
System.out.print("\nPlease enter amount of wins: \t");
int wins = scanner.nextInt();
System.out.print("\nPlease enter amount of losses: \t");
int losses = scanner.nextInt();
fighters.add(new Fighter(name, age, country, wins, losses));
System.out.println("Fighter Added!");
}
//Removes a fighter from ArrayList
public static void removeFighter(ArrayList<Fighter> fighters)
{
System.out.print("Please enter the name of the fighter you wish to remove: \t");
String name = scanner.nextLine();
for (Fighter fighter : fighters)
{
if (fighter.getName() == name)
{
fighters.remove(fighter);
}
}
}
public static void displayAllFighters(ArrayList<Fighter> fighters)
{
for (Fighter fighter : fighters)
{
System.out.println(fighter);
System.out.println("==========================================");
}
}
public static int countWinPercentLowerThan(ArrayList<Fighter> fighters , int value)
{
int count = 0;
for (Fighter fighter : fighters)
{
if (fighter.getPercent() < value)
{
count++;
}
}
return count;
}
public static int countWinPercentGreaterThan(ArrayList<Fighter> fighters , int value)
{
int count = 0;
for (Fighter fighter : fighters)
{
if (fighter.getPercent() > value)
{
count++;
}
}
return count;
}
}
Class that isn't being recognized.
package project;
public class Fighter
{
private String name;
private int age;
private String country;
private int wins;
private int losses;
public Fighter(String name, int age, String country, int wins, int losses)
{
this.name = name;
this.age = age;
this.country = country;
this.wins = wins;
this.losses = losses;
}
public Fighter(String name)
{
this.name = name;
this.age = 0;
this.country = "TBA";
this.wins = 0;
this.losses = 0;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return this.age;
}
public void setAge(int age)
{
this.age = age;
}
public String getCountry()
{
return this.country;
}
public void setCountry(String country)
{
this.country = country;
}
public int getWins()
{
return this.wins;
}
public void setWins(int wins)
{
this.wins = wins;
}
public int getLosses()
{
return this.losses;
}
public void setLosses(int losses)
{
this.losses = losses;
}
public String toString()
{
return "Fighter Name: " + this.name + ".\nFighter age: " + this.age + ".\nFighter nation: " + this.country + ".\nFighter wins: " + this.wins + ".\nFighter losses: " + this.losses + ".";
}
public void updateWin()
{
this.wins++;
}
public void updateLosses()
{
this.losses++;
}
public double getPercent()
{
int totalFights = this.wins + this.losses;
double percent = this.wins * 100/totalFights;
return percent;
}
}
Thank you in advanced!

Related

"For" loop issue at ArrayList method in Java

I have an issue at TestVolleyTeam.java. I cannot get the list arrays to work, I am honestly confused. I don't really know how to assign the lists with the "for" loop, I have probably made a mistake there.
The code is supposed to show the list of the players by using both the VolleyPlayer class and the VolleyTeam class through the TestVolleyTeam class. Can anyone spot the mistakes I've made?
class VolleyPlayer {
private String name;
private String surname;
private int flnum;
private int height;
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getFlnum() {
return flnum;
}
public int getHeight() {
return height;
}
public VolleyPlayer(String n, String sur, int fl, int h) {
name = n;
surname = sur;
flnum = fl;
height = h;
}
public VolleyPlayer(String n, String sur, int fl) {
this(n, sur, fl, 185);
}
public VolleyPlayer(String n, String sur) {
this(n, sur, 3);
}
public VolleyPlayer(String n) {
this(n, "Brown");
}
}
import java.util.ArrayList;
public class VolleyTeam {
private String teamname;
private String city;
private int year;
private ArrayList<VolleyPlayer> players;
public String getTeamname() {
return teamname;
}
public String getCity() {
return city;
}
public int getYear() {
return year;
}
public ArrayList<VolleyPlayer> getPlayers() {
return players;
}
public void setTeamname(String newTeamname) {
this.teamname = teamname;
}
public void setCity(String newCity) {
this.city = city;
}
public void setYear(int newYear) {
this.year = year;
}
public void setPlayers(ArrayList<VolleyPlayer> newPlayers) {
this.players = players;
}
}
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.util.ArrayList;
public class TestVolleyTeam {
public static void main(String[] args) {
VolleyTeam myObj = new VolleyTeam();
String teamname = JOptionPane.showInputDialog(null, "What is the name of the team?", "Input");
myObj.setTeamname(teamname);
String city = JOptionPane.showInputDialog(null, "What is the city of the team?", "Input");
myObj.setCity(city);
String input = JOptionPane.showInputDialog(null, "What is the foundation year of the team?",
"Input");
int year = Integer.parseInt(input);
myObj.setYear(year);
myObj.getTeamname();
myObj.getCity();
myObj.getYear();
VolleyPlayer first = new VolleyPlayer("Michael", "Scott", 1, 175);
VolleyPlayer second = new VolleyPlayer("Jim", "Halpert", 2, 191);
VolleyPlayer third = new VolleyPlayer("Dwight", "Schrute", 3, 189);
VolleyPlayer fourth = new VolleyPlayer("Darryl", "Philbin", 4, 188);
VolleyPlayer fifth = new VolleyPlayer("Andy", "Bernard", 5, 182);
VolleyPlayer sixth = new VolleyPlayer("Oscar", "Martinez", 6, 173);
VolleyPlayer seventh = new VolleyPlayer("Stanley", "Hudson", 7, 180);
VolleyPlayer eighth = new VolleyPlayer("Kevin", "Malone", 8, 185);
VolleyPlayer ninth = new VolleyPlayer("Creed", "Bratton", 9, 183);
VolleyPlayer tenth = new VolleyPlayer("Toby", "Flederson", 10, 177);
ArrayList<VolleyPlayer> vplist = new ArrayList<VolleyPlayer>();
for (VolleyPlayer volleyPlayer : vplist) {
vplist.add(volleyPlayer);
}
myObj.getPlayers();
myObj.setPlayers(vplist);
ArrayList<VolleyPlayer> vplist2 = volleyTeam.getPlayers();
for (VolleyPlayer volleyPlayer : vplist2) {
vplist2.add(volleyPlayer);
}
volleyTeam.getPlayers();
volleyTeam.setPlayers(vplist2);
JOptionPane.showMessageDialog(null, vplist2, teamname + " " + city + ", " + year,
JOptionPane.INFORMATION_MESSAGE);
}
}
The List is empty when you start, this code
for (VolleyPlayer volleyPlayer : vplist) {
is attempted to loop over an empty List. I think I see what you want, and it can be achieved with something like
List<VolleyPlayer> vplist = new ArrayList<>(Arrays.asList(
first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth));
Then you don't need a loop to add first - tenth to your vplist. Note I changed it the diamond operator <> on construction. And used Arrays.asList to add the elements.
Since you must use a for loop, create an inline array. Like,
for (VolleyPlayer volleyPlayer : new VolleyPlayer[] {
first, second, third, fourth, fifth, sixth, seventh,
eighth, ninth, tenth }) {

Java Store multiple phone number for one user

Question: Store more than 1 user data with id, name, weight, age, and phone number (can have multiple phone number)
How do I store multiple phone number for one user?
I facing an error "Exception in thread "main" java.lang.NullPointerException at Store_User.main(Store_User.java:29). Anyone can solve it?
import java.util.List;
public class User {
private int usrid;
private String name;
private double weight;
private int age;
private List<String> Pnum;
public User(int usrid, String name, double weight, int age, List<String> Pnum){
this.usrid = usrid;
this.name = name;
this.weight = weight;
this.age = age;
}
public void setUsrid(int usrid) {
this.usrid = usrid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getPnum() {
return Pnum;
}
public void setPnum(List<String> pnum) {
Pnum = pnum;
}
int getUID(){
return usrid;
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class Store_User {
public static void main(String[] args) {
User usr1 = new User(1,"Mark", 55.5, 26, Arrays.asList("0140392812", "0123456789"));
User usr2 = new User(2, "Ken", 54.7, 33, Arrays.asList("0129876543"));
User usr3 = new User(3, "Callie", 62.3, 34, Arrays.asList("06123456", "0987654322", "01798654321"));
ArrayList<User> ulist = new ArrayList<User>();
ulist.add(usr1);
ulist.add(usr2);
ulist.add(usr3);
Iterator itr=ulist.iterator();
while(itr.hasNext()){
User usr = (User)itr.next();
System.out.println(usr.getUID() +", " + usr.getName() +", " + usr.getAge() +", " + usr.getWeight());
String out ="";
for(String number: usr.getPnum()){
out += number + ";";
}
System.out.println(out);
}
}
}
Chat conversation end
EDIT: Phone numbers are stored as an ArrayList of Strings and are "linked" to the usrId since they are non-static members of the same class, hence each User object will have it's own id and list of numbers. You can access the phone numbers of a user using:
usr.getPnum()
where usr is an instance of User.java, this will return a ArrayList<String> representing the phone numbers, if you want a specific number you can access the list by index like so:
usr.getPnum().get(0) //The index in this case is 0
User.java
import java.util.List;
public class User {
private int usrid;
private String name;
private double weight;
private int age;
private List<String> Pnum;
public User(int usrid, String name, double weight, int age, List<String> Pnum){
this.usrid = usrid;
this.name = name;
this.weight = weight;
this.age = age;
this.Pnum = Pnum;
}
public void setUsrid(int usrid) {
this.usrid = usrid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getPnum() {
return Pnum;
}
public void setPnum(List<String> pnum) {
Pnum = pnum;
}
int getUID(){
return usrid;
}
}
Store_User.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class Store_User {
public static void main(String[] args) {
User usr1 = new User(1,"Tee Ting Ong", 55.5, 26, Arrays.asList("00000000", "00000000", "00000000"));
User usr2 = new User(2, "Tee Soon Teh", 54.7, 33, Arrays.asList("00000000", "00000000"));
User usr3 = new User(3, "Tee Ting Ken", 62.3, 34, Arrays.asList("00000000"));
ArrayList<User> ulist = new ArrayList<User>();
ulist.add(usr1);
ulist.add(usr2);
ulist.add(usr3);
Iterator itr=ulist.iterator();
while(itr.hasNext()){
User usr = (User)itr.next();
System.out.println(usr.getUID() +", " + usr.getName() +", " + usr.getAge() +", " + usr.getWeight());
//This print out the numbers
String out = "";
for(String number : usr.getPnum()){
out += number + ";";
}
System.out.println(out);
}
}
}

Converting separate "double" values into an Array within an ArrayList

I have created a program that contains an ArrayList with separated "double" values for student grades. However, the course calls for creating an int Array of grades, instead of the separate values I had previously.
My code for Student Class (I have deleted irrelevant code to cut to the chase):
public class Student {
private int[] Grades = new int[3];
public Student(String stuid, String fname, String lname, String email, int age, int[] grades) {
this.Grades = grades;
}
public int[] getGrades() {
return Grades;
}
public void setGrades(int[] grades) {
Grades = grades;
}
public String toString() {
return String.format("StuID: %s\t First Name: %s\t Last Name: %s\t E-Mail: %s\t Age: %s\t Grades: %s\t",
this.StuID, this.FName, this.LName, this.Email, this.Age, this.Grades);
}
}
Roster Class:
import java.util.ArrayList;
public class Roster {
static ArrayList<Student> studentArray;
public Roster(ArrayList<Student> ar) {
studentArray = ar;
}
// 3.C - Print Average Grade
public static void print_average_grade(String studentID) {
for (Student v : studentArray) {
if (v.getStuID().equals(studentID)) {
double total = v.getGrade1() + v.getGrade2() + v.getGrade3();
double average = total / 3;
System.out.println("Student ID#" + studentID + " Grade AVG= " + average);
}
}
}
public static void main(String[] args) {
ArrayList<Student> studentArray = new ArrayList<Student>();
studentArray.add(new Student("1", "John", "Smith", "John1989#gmail.com", 20, 88, 79, 59));
studentArray.add(new Student("2", "Susan", "Erickson", "Erickson_1990#gmailcom", 19, 91, 72, 85));
studentArray.add(new Student("3", "Jack", "Napoli", "The_lawyer99yahoo.com", 19, 85, 84, 87));
studentArray.add(new Student("4", "Erin", "Black", "Erin.black#comcast.net", 22, 91, 98, 82));
studentArray.add(new Student("5", "Captain", "Planet", "PowIsYours#planet.edu", 65, 99, 98, 97));
new Roster(studentArray);
for (Student v : studentArray) {
print_average_grade(v.getStuID());
}
}
}
I have changed the separated values (Grade1, Grade2, Grade3) into an "int[] Grades" array and modified the constructor and have added the setter and the getter. So, I think the Student class is good to go, however the Roster class, is where I am stuck. Two things:
1) How do I add values of the Grades into the Array that is now a part of the ArrayList?
2) How would I adjust my AVG Grade method to perform the same task as before but with the values of the Array?
Any help would be great because I have been stuck on this for days.
Thanks.
P.S. If posting the full code would be easier, I will gladly post it for any aid on this problem.
I tried to fix your code according to the two requirements (array, AVG). Please see the following codes (I have tested it).
Student Class:
public class Student {
String StuID;
String FName;
String LName;
String Email;
int Age;
private int[] Grades = new int[3];
public Student(String stuid, String fname, String lname, String email, int age, int[] grades) {
this.StuID = stuid;
this.FName = fname;
this.LName = lname;
this.Email = email;
this.Grades = grades;
}
public int[] getGrades() {
return Grades;
}
public void setGrades(int[] grades) {
Grades = grades;
}
public String toString() {
return String.format("StuID: %s\t First Name: %s\t Last Name: %s\t E-Mail: %s\t Age: %s\t Grades: %s\t", this.StuID, this.FName, this.LName, this.Email, this.Age, this.Grades);
}
public String getFName() {
return FName;
}
public void setFName(String fName) {
FName = fName;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public String getStuID() {
return StuID;
}
public void setStuID(String stuID) {
StuID = stuID;
}
public String getLName() {
return LName;
}
public void setLName(String lName) {
LName = lName;
}
}
Roster Class:
import java.util.ArrayList;
public class Roster {
ArrayList<Student> studentArray;
public Roster(ArrayList<Student> ar) {
studentArray = ar;
}
// 3.C - Print Average Grade
public void print_average_grade(String studentID) {
for (Student v : studentArray) {
if (v.getStuID().equals(studentID)) {
double total = v.getGrades()[0] + v.getGrades()[1] + v.getGrades()[2];
double average = total / 3;
System.out.println("Student ID#" + studentID + " Grade AVG= " + average);
}
}
}
public static void main(String[] args) {
ArrayList<Student> studentArray = new ArrayList<Student>();
int[] grades1 = {88, 79, 59};
int[] grades2 = {91, 72, 85};
int[] grades3 = {85, 84, 87};
int[] grades4 = {91, 98, 82};
int[] grades5 = {99, 98, 97};
studentArray.add(new Student("1", "John", "Smith", "John1989#gmail.com", 20, grades1));
studentArray.add(new Student("2", "Susan", "Erickson", "Erickson_1990#gmailcom", 19, grades2));
studentArray.add(new Student("3", "Jack", "Napoli", "The_lawyer99yahoo.com", 19, grades3));
studentArray.add(new Student("4", "Erin", "Black", "Erin.black#comcast.net", 22, grades4));
studentArray.add(new Student("5", "Captain", "Planet", "PowIsYours#planet.edu", 65, grades5));
Roster r = new Roster(studentArray);
for (Student v : studentArray) {
r.print_average_grade(v.getStuID());
}
}
}
Output:
Student ID#1 Grade AVG= 75.33333333333333
Student ID#2 Grade AVG= 82.66666666666667
Student ID#3 Grade AVG= 85.33333333333333
Student ID#4 Grade AVG= 90.33333333333333
Student ID#5 Grade AVG= 98.0
Here's how I did the same project. Mine is still being graded, so I have no idea if it will pass the first time or not. But maybe it will help someone by my sharing it.
import java.util.ArrayList;
public class Roster {
public static ArrayList<Student> students = new ArrayList<>();
public static void main(String[] args)
{
// input student grades
int[] grade0 = {0,0,0}; // filler to make grade array equal to student ID
int[] grade1 = {88, 79, 59};
int[] grade2 = {91, 72, 85};
int[] grade3 = {85, 84, 87};
int[] grade4 = {91, 98, 82};
int[] grade5 = {99, 98, 97};
// input student info
addStudent(0, "null", "null", "null#null.com", 0, grade0); // filler to align student ID with array number
addStudent(1, "John", "Smith", "John1989#gmail.com", 20, grade1);
addStudent(2, "Suzan", "Erickson", "Erickson_1990#gmailcom", 19, grade2);
addStudent(3, "Jack", "Napoli", "The_lawyer99yahoo.com", 19, grade3);
addStudent(4, "Erin", "Black", "Erin.black#comcast.net", 22, grade4);
addStudent(5, "Habib", "Trump", "someemail#mywqu.edu", 42, grade5);
// printing related subroutines/methods
Student student = students.get(3); //get student 3 for printing
System.out.println("Print one student:");
student.print(); //prints specific student data as per 2.D
printAllStudents(); //print all students as per 3.B
print_invalid_emails(); //checks email addresses for proper form as per 3.D
printAverageGrade(); //print grades as per 3.C
remove(); // removes student 5 as per 3.A
printAllStudents(); // shows student 3 has been removed
remove(); // shows error as student already removed
}
public static void addStudent(int studentID, String firstName, String lastName, String email, int age, int[] grades){
Student newStudent = new Student(studentID, firstName, lastName, email, age, grades);
students.add(newStudent);
}
public static void remove(){ // remove student
try{
System.out.println("Remove student: 5 ");
students.remove(5);
} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: No such student ID");
}}
public static void printAverageGrade(){ // print Average Grade
System.out.println("Print Average Grade: ");
for(Student eachItem : students){
double total = eachItem.getgrades()[0] + eachItem.getgrades()[1] + eachItem.getgrades()[2];
double average = total / 3;
System.out.println(average);
}}
public static void printAllStudents(){ // print All Students
System.out.println("Print all Students: ");
for(int i=0; i < students.size(); i++){
students.get(i).print();
}}
public static void print_invalid_emails(){ // check Email Addresses for proper form
System.out.println("Check for proper form of email addresses: ");
for(Student student : students) {
if (student.getemail().contains("#") && student.getemail().contains(".") && !student.getemail().contains(" ")){
System.out.println("Passed format check");
}
else
{
System.out.println("Invalid email address");
}}
}}
public class Student extends Roster
{
private int studentID;
private String firstName;
private String lastName;
private String email;
private int age;
private int[] grades = new int[3];
public Student(int studentID, String firstName, String lastName, String email, int age, int[] grades)
{
setstudentID(studentID);
setfirstName(firstName);
setlastName(lastName);
setemail(email);
setage(age);
setgrades(grades);
}
public int getstudentID(){
return studentID;
}
public void setstudentID(int studentID)
{
this.studentID = studentID;
}
public String getfirstName(){
return firstName;
}
public void setfirstName(String firstName)
{
this.firstName = firstName;
}
public String getlastName(){
return lastName;
}
public void setlastName (String lastName)
{
this.lastName = lastName;
}
public String getemail(){
return email;
}
public void setemail(String email)
{
this.email = email;
}
public int getage(){
return age;
}
public void setage(int age)
{
this.age = age;
}
public void setgrades(int[] grades){
this.grades = grades;
}
public int[] getgrades(){
return grades;
}
public void print(){
System.out.println(
"Student ID = \t" + getstudentID() + ", \t" +
"First Name = \t" + getfirstName() + ", \t" +
"Last Name = \t" + getlastName() + ", \t" +
"Email = \t" + getemail() + ", \t" +
"Age = \t" + getage());
}
}

Finding and removing a name in an ArrayList

Basically i am trying to search for specif names in an Array-list and then remove just that name.I am doing an assignment for college, and it species to search and remove by name, so i cant use the int index of, I am fairly new to java, so ill post my code maybe I am missing something any help would be great.
import java.util.ArrayList;
public class GaaClub {
private ArrayList<Member> players;
{
}
public GaaClub() {
players = new ArrayList<Member>();
}
public void addStanderedMember() {
// create a message object:
StdOut.println("Please enter the members's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the members address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the members DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the amount to Pay: ");
double mempaid = StdIn.readDouble();
Member player = new Member(name, address, dob, mempaid);
players.add(player);
}
public void addStandaredPlayer() {
// create a message object:
StdOut.println("Please enter the standard Player's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the standard Player's address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the standard Player's DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the amount to Pay: ");
double mempaid = StdIn.readDouble();
StandardPlayer player = new StandardPlayer(name, address, dob, mempaid);
players.add(player);
}
public void addElitePlayer() {
// create a message object:
StdOut.println("Please enter the Elite Players's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the Elite Players's address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the Elite Players's DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the the amount to Pay: ");
double mempaid = StdIn.readDouble();
StdOut.println("Please enter the Elite Players's BMI: ");
double bmi = StdIn.readDouble();
StdOut.println("Please enter the Elite Players's height: ");
double height = StdIn.readDouble();
ElitePlayer player = new ElitePlayer(name, address, dob, mempaid, bmi,
height);
players.add(player);
}
public static void main(String[] args) {
GaaClub app = new GaaClub();
app.run();
}
public void memberType() {
StdOut.println("Enter Type of membership: ");
StdOut.println("1) Add a Standard Member");
StdOut.println("2) Add an Elite Player");
StdOut.println("3) Add a Standard Player");
String memberchoice = StdIn.readString();
if (memberchoice.equals("1"))
addStanderedMember();
if (memberchoice.equals("2"))
addElitePlayer();
if (memberchoice.equals("3"))
addStandaredPlayer();
}
public void listNames() {
for (Member player : players) {
player.list();
}
}
public void removeName() {
for (Member player : players) {
listNames();
String sResponse = StdIn.readString();
if (sResponse.equals(player.name))
{
players.remove(player);;
return;
}
}
}
private int mainMenu() {
StdOut.println("1) Add a Member");
StdOut.println("2) Remove Player");
StdOut.println("3) List Names");
StdOut.println("4) List Members");
StdOut.println("0) Exit");
StdOut.print("==>>");
int option = StdIn.readInt();
return option;
}
public void run() {
{
StdOut.println("Posts");
int option = mainMenu();
while (option != 0) {
switch (option) {
case 1:
memberType();
break;
case 2:
removeName();
break;
case 3:
addStanderedMember();
break;
case 4:
listNames();
break;
}
option = mainMenu();
}
StdOut.println("Exiting...");
}
}
}
And Second file:
import java.util.ArrayList;
public class Member {
protected String name;
protected String address;
protected String dob;
protected double mempaid;
public Member(String name, String address, String dob, double mempaid) {
this.name = name;
this.address = address;
this.dob = dob;
this.mempaid = mempaid ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDob() {
return dob;
}
public void list(){
System.out.println(name);
}
public void setDob(String dob) {
this.dob = dob;
}
public double getMempaid() {
return mempaid;
}
public void setMempaid(double mempaid) {
this.mempaid = mempaid;
}
#Override
public String toString() {
return "Member [name=" + name + ", address=" + address + ", dob=" + dob
+ ", mempaid=" + mempaid + "]";
}
}
import java.util.ArrayList;
public class StandardPlayer extends Member {
private ArrayList<Competition> competition;
public StandardPlayer(String name, String address, String dob,
double mempaid) {
super(name, address, dob, mempaid);
}
public ArrayList<Competition> getCopmetition() {
return competition;
}
public void setCopmetition(ArrayList<Competition> copmetition) {
this.competition = copmetition;
}
void addCompetiton(Competition c) {
}
void payMembership(double amt) {
mempaid = 0;
}
#Override
public String toString() {
return "StandardPlayer [competition=" + competition + ", name=" + name
+ ", address=" + address + ", dob=" + dob + ", mempaid="
+ mempaid + "]";
}
}
And third file:
import java.util.ArrayList;
public class ElitePlayer extends Member {
private double bmi;
private double height;
private ArrayList<Competition> competition;
public ElitePlayer(String name, String address,
String dob, double mempaid, double bmi, double height) {
super(name, address, dob, mempaid);
this.bmi = bmi;
this.height = height;
}
public double getBmi() {
return bmi;
}
public void setBmi(double bmi) {
this.bmi = bmi;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public ArrayList<Competition> getCopmetition() {
return competition;
}
void payMembership(double amt) {
mempaid = 0;
}
#Override
public String toString() {
return "ElitePlayer [bmi=" + bmi + ", height=" + height
+ ", competition=" + competition + ", name=" + name
+ ", address=" + address + ", dob=" + dob + ", mempaid="
+ mempaid + "]";
}
public void setCompetition(ArrayList<Competition> competition) {
this.competition = competition;`enter code here`
}
}
ArrayList has a method which can remove by Object:
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob");
arr.remove("Bob");
it removes the first instance of the object.
You could of course simulate the same debavior:
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob");
String searchTerm = "Bob";
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).equals(searchTerm) {
arr.remove(i);
break;
}
}
This deviation from the built in method would only be recommended if you wanted to have the search delete on some other, or similar condition. For example if it contained the word "Bob"...
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob Bobingston");
String searchTerm = "Bob";
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).contains(searchTerm)) {
arr.remove(i);
break;
}
}
It seems as if you already have a loop set-up for it. Just loop through the members, check if the name equals what you're looking for, then remove that member from the list if it is
for(Member mem : players) { //loop through each member in list
if(mem.getName().equalsIgnoreCase("name")) { //check if member's name is "name"
players.remove(mem); //removes member from list if it is
}
}
equalsIgnoreCase(String) checks the string without checking for case sensitivity. It won't care for capitalization. If you care about capitalization, use equals(String)

How to make an array of child objects

I have an assignment from my professor and I can't figure out how to properly create an array of objects. None of the classes but the Client class can be changed; the interface can't be changed either. I'm supposed to be able to create an array of objects from several subclasses and be able to access all of the methods.
Here is my error report:
MathewBorumP5.java:68: error: cannot find symbol
revenue = movies[x].calcRevenue();
^
symbol: method calcRevenue()
location: class Movie
MathewBorumP5.java:70: error: cannot find symbol
movies[x].getYear(), movies[x].calcRevenue(),
^
symbol: method calcRevenue()
location: class Movie
MathewBorumP5.java:71: error: cannot find symbol
movies[x].calcProfit(revenue), movies[x].categor
y());
^
symbol: method calcProfit(double)
location: class Movie
MathewBorumP5.java:71: error: cannot find symbol
movies[x].calcProfit(revenue), movies[x].categor
y());
^
symbol: method category()
location: class Movie
MathewBorumP5.java:78: error: cannot find symbol
totalRevenue = totalRevenue + movies[x].calcRevenue();
^
symbol: method calcRevenue()
location: class Movie
MathewBorumP5.java:81: error: cannot find symbol
"%.3f million dollars.", Movie[0].getTotalMovies(), tota
lRevenue);
^
symbol: variable Movie
location: class MathewBorumP5
6 errors
My client class:
import java.util.Scanner;
public class MathewBorumP5 {
public static void main(String[] args) {
int choice;
boolean restart = true;
Scanner input = new Scanner(System.in);
Movie[] movies = new Movie[6];
movies[0] = new Animated("Beauty and the Beast", "Gary Trousdale", 1991,
10.0, 5.0, 2.0);
movies[1] = new Animated("Peter Pan", "Clyde Geronimi", 1953, 2.0, 1.2,
.5);
movies[2] = new Documentary("Planet Earth", "Alastair Fothergill", 2006,
10, 20, 5);
movies[3] = new Documentary("Drain the Ocean", "Steve Nichols", 2009, 9,
2,3);
movies[4] = new Drama("The Shawshank Redemption", "Frank Darabont",
1994, 89, 7, 2);
movies[5] = new Drama("The Godfather", "Francis Coppola", 1972, 10, 3,
5);
do {
menu();
System.out.print("Enter a number from 1 - 5: ");
choice = input.nextInt();
System.out.print("\n");
switch(choice) {
case 1:
item1(movies);
break;
case 2:
item2(movies);
break;
case 3:
break;
case 4:
break;
case 5:
restart = false;
break;
default:
System.out.print("You didn't enter a number between 1"
+ " and 5.\n");
break;
}
} while(restart == true);
}
public static void menu() {
System.out.print("Warren Moore Movie Menu\n");
System.out.print("1. Show the list of movies in the array\n");
System.out.print("2. Display the total number of movies and the total" +
" revenues\n");
System.out.print("3. Search movie by title\n");
System.out.print("4. Display movies sorted by profit in decreasing" +
" order\n");
System.out.print("5. Exit\n");
}
public static void item1(Movie[] movies) {
double revenue;
System.out.printf("%-26s%-6s%-10s%-9s%-11s\n", "Title", "Year",
"Revenue", "Profit", "Category");
for(int x = 0; x <= 6; x++) {
revenue = movies[x].calcRevenue();
System.out.printf("%-26s%-6s%-10s%-9s%-11s\n", movies[x].getTitle(),
movies[x].getYear(), movies[x].calcRevenue(),
movies[x].calcProfit(revenue), movies[x].category());
}
}
public static void item2(Movie[] movies) {
double totalRevenue;
for(int x = movies[0].getTotalMovies(); x > 0; x--) {
totalRevenue = totalRevenue + movies[x].calcRevenue();
}
printf("The total number of moves is %d, and their total revenue is" +
"%.3f million dollars.", Movie[0].getTotalMovies(), totalRevenue);
}
}
My Superclass:
public class Movie {
protected String title;
protected String director;
protected int year;
protected double productionCost;
private static int totalMovies = 0;
public Movie() {
totalMovies++;
}
public Movie(String newTitle, String newDirector, int newYear,
double newCost) {
totalMovies++;
title = newTitle;
director = newDirector;
year = newYear;
productionCost = newCost;
}
public int getTotalMovies() {
return totalMovies;
}
public String getTitle() {
return title;
}
public void setTitle(String newTitle) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getProductionCost() {
return productionCost;
}
public void setProductionCost(double productionCost) {
this.productionCost = productionCost;
}
public String toString() {
return "";
}
}
Class template(all my classes are basically the same):
public class Animated extends Movie implements Profitable {
private double rate;
private double income;
public Animated() {
super();
}
public Animated(String title, String director, int year, double cost,
double rate, double income) {
super(title, director, year, cost);
this.rate = rate;
this.income = income;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public double getIncome() {
return income;
}
public void setIncome(double income) {
this.income = income;
}
public String category() {
return "Animated";
}
public double calcRevenue() {
return (income * rate);
}
public double calcProfit(double revenue) {
return (revenue - super.productionCost);
}
public String toString() {
return (super.toString() + "");
}
}
My interface:
public interface Profitable {
public abstract String category();
public abstract double calcRevenue();
public abstract double calcProfit(double revenue);
}
You need to add appropriate cast and test using instanceof.
revenue = movies[x].calcRevenue();
must be replaced by
if (movies[x] instanceof Profitable) {
revenue = ((Profitable)movies[x]).calcRevenue();
} else {
// decide what to do if movie if not profitable that is to say does not have the calcRevenue method
}

Categories