I am trying to get the length of the longest first name and saving it as int longest, but my code is not properly fetching the first names from my class Student
here is my code:
public static int findLongestFirstName(ArrayList<Student> studentList)
{
int longest = 0;
for (int i = 0; i < studentList.size(); i++)
{
if (studentList.get(i).getFirstName.length() > longest);
{
longest = studentList.get(i).getFirstName.length();
}
}
return longest;
}
Here is where I am fetching my variables:
public class Student
{
private int IDnum;
private String firstName;
private String lastName;
private int gradYear;
private double gradePoint;
public Student(int ID, String first, String last, int year, double GPA)
{
IDnum = ID;
firstName = first;
lastName = last;
gradYear = year;
gradePoint = GPA;
}
public int getID()
{
return IDnum;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getYear()
{
return gradYear;
}
public double getGPA()
{
return gradePoint;
}
}
getFirstName is not a variable, it's a method. Java syntax requires parentheses when calling a method (even if the method takes no arguments):
if (studentList.get(i).getFirstName().length() > longest);
^^
(and on the next line).
By the way, you can replace the entire if construct with:
longest = Math.max(studentList.get(i).getFirstName().length(), longest);
To simplify this further, you could use a for-each loop:
public static int findLongestFirstName(ArrayList<Student> studentList)
{
int longest = 0;
for (Student student : studentList) {
longest = Math.max(student.getFirstName().length(), longest);
}
return longest;
}
Your code seems fine however there is a semi colon at the end of your if statement which is causing the issue.
Related
Apologies for the poor title but I don't know how to phrase my issue. I am attempting to call the getSSN method from the Student class in my BubbleSorter class after a few students have been placed in an ArrayList. How can I call for the specific SSN variable. I understand why the error is occuring, but not how to change it to make it work. The error message is as follows: The method getSSN() is undefined for the type SearchandSort.
My Student Class:
public class Student {
private String firstName, lastName;
private int SSN;
public Student(String first, String last, int ssn) {
firstName = first;
lastName = last;
SSN = ssn;
}
public String toString() {
return lastName + ", " + firstName + " " + SSN + "\t";
}
public boolean equals(Object other) {
return (lastName.equals(((Student)other).getLastName()) && firstName.equals(((Student)other).getFirstName()) && (SSN == (((Student)other).getSSN())));
}
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 int getSSN() {
return SSN;
}
public void setSSN(int SSN) {
this.SSN = SSN;
}
}
My BubbleSorter:
import java.lang.reflect.Array;
// “On my honor, I have neither received nor given any unauthorized assistance on this examination.”
public class BubbleSorter {
public static void bubbleSort(SortandSearch Students[]) {
int lastPos;
int index;
int temp;
for (lastPos = Students.length-1; lastPos >= 0; lastPos--) {
for (index = 0; index <= lastPos - 1; index++) {
if (((Students[index]).getSSN()) - ((Students[index+1].getSSN())) > 0) {
temp = Students[index].getSSN();
Students[index].getSSN() = Students[index+1].getSSN();
Students[index+1].getSSN() = temp;
}
}
}
}
}
My main class:
import java.util.ArrayList;
import java.util.Scanner;
public class SortandSearch {
public static void main(String[] args) {
Student a = new Student("Ryan", "Jones", 123456);
Student b = new Student("Jolie", "Decker", 123457);
ArrayList<Student> Students = new ArrayList<Student>();
Students.add(a);
Students.add(b);
System.out.println(Students);
bubbleSort(Students);
System.out.println(Students);
System.out.println("Please enter the SSN of the student you are searching for:");
Scanner scan = new Scanner(System.in);
int searchKey = scan.nextInt();
for (int index = 0; index < Students.size(); index++) {
if (Students.get(index).getSSN() == searchKey) {
System.out.print("The student with SSN " + searchKey + " is located at " + index);
}
}
}
}
EDIT:
The error now shows: The type of the expression must be an array type but it resolved to ArrayList.
New BubbleSorter:
import java.util.ArrayList;
// “On my honor, I have neither received nor given any unauthorized assistance on this examination.”
public class BubbleSorter {
public static void bubbleSort(ArrayList<Student> studentList) {
int lastPos;
int index;
int temp;
for (lastPos = studentList.size()-1; lastPos >= 0; lastPos--) {
for (index = 0; index <= lastPos - 1; index++) {
if ((studentList.get(index).getSSN()) - ((studentList.get(index).getSSN())) > 0) {
temp = studentList[index];
studentList[index] = studentList[index+1];
studentList[index+1] = temp;
}
}
}
}
}
There seem multiple things wrong to this code. I think you are trying unnessecary casting your arraylist to something else
First, I think your function signature should change to
public static void bubbleSort(ArrayList<Student> studentList)
And then you can access the elements with:
studentList.get(index).getSSN()
In SortandSearch you put instances of Student into ArrayList<>, and the your bubbleSort method must also take argument of this type or at least List and then convert it to array and return sorted list:
public static List<Student> bubbleSort(List<Student> studentsList) {
Student[] Students = studentsList.toArray(new Student[studentsList.size()]);
// ...
return Arrays.asList(Students);
}
And in the calling main method you need to store sorted list:
List<Student> sorted = BubbleSorter.bubbleSort(Students);
System.out.println(sorted);
This question already has answers here:
How do I remove objects from an array in Java?
(20 answers)
Closed 5 years ago.
How can I remove a student from the course by using the drop method down below? I tried by accessing the roll book for the course parameter.
But I do not how to remove the student id from the roll book.
public static class Student {
private int studentID;
private String first;
private String last;
private int credits;
private boolean graduate;
public Student(int id, String first, String last, boolean graduate) {
this.studentID = id;
this.first = first;
this.last = last;
this.graduate = graduate;
}
public int getID() { return studentID; }
public String getFirstName() { return first; }
public String getLastName() { return last; }
public int getCredits() { return credits; }
public boolean isGraduate() { return graduate; }
public void setCredits(int credits) { this.credits = credits; }
public String toString() { return "[" + studentID + "] " + first + " " + last; }
public boolean isEnrolled(Course c) {
return (c.findRollBookEntry(this.getID()) != null);
}
public void drop(Course c) {
for(int i = 0; i<c.getRollBook().length; i++){
c.findRollBookEntry(i).getStudent();
}
}
}
If you are using an array list and passing new objects each time a data is entered you can iterate through the arraylist on the delete function and do something like
If(i.getID()==id_entered) {i.remove();}
I'm trying to do this exercise: i have a student that has a name,surname and a number, i want to order the students by number..if i want to order by name or surname it seems easy but with number i don't know how to do..
this is my code:
public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;
public Student(String n, String s, int m) {
name = n;
surname = s;
number = m;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getmatricola() {
return number;
}
//CompareTo Name
public int compareTo(Student otherObject) {
return name.compareTo(otherObject.getName());
}
}
//TESTER
ArrayList<Student> list = new ArrayList<Student>();
System.out.print("\n ORDER BY NUMBER \n");
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
Student s = list.get(i);
String std = s.getAll();
System.out.println(std);
}
You can implement something like:
public int compareTo(Student otherObject) {
return Integer.compare(this.number, otherObject.getNumber());
}
So why you number is an int you can substract the number and return the difference:
public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;
public Student(String n, String s, int m) {
name = n;
surname = s;
number = m;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getmatricola() {
return number;
}
//CompareTo number
public int compareTo(Student otherObject) {
return number - otherObject.getmatricola();
}
}
Try doing this...should work
//CompareTo Name
public int compareTo(Student otherObject) {
if( this.getmatricola() > otherObject.getmatricola())
return 1;
else
return -1;
}
I don't see what I'm doing wrong here or how anything here is static without it being declared that way. I just need to be pointed in the right direction here.
Test code:
public class PaintballPlayerTest
{
//Test program for PaintballPlayer assignment
public static void main (String [] args)
{
//Part 1 check constructor & toString --(make sure ID is working too)
PaintballPlayer sheldon = new PaintballPlayer ("Sheldon", "Lee", "Cooper");
PaintballPlayer leonard = new PaintballPlayer ("Leonard", "Hofstadter");
PaintballPlayer amy = new PaintballPlayer ("Amy", "Farrah", "Fowler");
System.out.println(sheldon);
System.out.println(leonard);
//Part 2 test getTotalPlayer --should be 3
System.out.println("The team has this many players " + PaintballPlayer.getTotalPlayers());
My code:
import java.util.*;
public class PaintballPlayer
{
private String firstName, middleName, lastName;
private String secFirst, secLast;
private int id;
private int count;
private static int totalPlayers;
private int playerID;
private int players;
public PaintballPlayer(String first, String middle, String last)
{
count = 0;
id = totalPlayers++;
players = count++;
firstName = first;
middleName = middle;
lastName = last;
}
public PaintballPlayer(String f, String l)
{
this (f,"",l);
id = count++;
}
public PaintballPlayer()
{
totalPlayers++;
}
public static int getTotalPlayers()
{
return totalPlayers;
}
public String toString()
{
String name;
String n;
name = firstName + " " + middleName + " " + lastName;
return name;
}
public int getPlayerID()
{
playerID = count;
return playerID;
}
}
Again, my problem is with the getTotalPlayers() method.
EDIT: This is my edited code applying the fixes provided. Thank you!
getTotalPlayers() is not a static method, so you need an instance of PaintballPlayer to call this method.
If you want to store the total players inside PaintballPlayer, you need an static attribute (same reference for all instances):
class PaintballPlayer {
private static int totalPlayers;
public PaintballPlayer() {
totalPlayers++;
}
public static int getTotalPlayers() {
return totalPlayers;
}
}
On your code there are a few problems, on the constructor #1
public PaintballPlayer(String first, String middle, String last)
{
count = 0;
players = 0;
id = count++;
players = count++;
firstName = first;
middleName = middle;
lastName = last;
}
The variables players and count are being reseted while the variable count is increased two times.
And in the constructor #2 the problem is worst:
public PaintballPlayer(String f, String l)
{
this (f,"",l);
id = count++;
players = count++;
}
because you are increasing the value of count two times besides the 2 times in the original constructor, so four times in total.
Once u have done what Devon Freese says u will have to modify the constructor of PaintballPlayer
public PaintballPlayer(String first, String middle, String last)
{
id = totalPlayers++;
firstName = first;
middleName = middle;
lastName = last;
}
Try this.
import java.util.*;
public class PaintballPlayer {
private String firstName, middleName, lastName;
private String secFirst, secLast;
private int id;
private static int count;
private static int totalPlayers;
private int playerID;
private static int players;
public PaintballPlayer(String first, String middle, String last) {
count++;
id = count;
players = count;
firstName = first;
middleName = middle;
lastName = last;
}
public PaintballPlayer(String f, String l) {
this(f, "", l);
id = count;
players = count;
}
public String toString() {
String name = firstName + " " + middleName + " " + lastName;
return name;
}
public static int getTotalPlayers() {
totalPlayers = players;
return totalPlayers;
}
public int getPlayerID() {
playerID = count;
return playerID;
}
}
class PaintballPlayerTest {
//Test program for PaintballPlayer assignment
public static void main(String[] args) {
//Part 1 check constructor & toString --(make sure ID is working too)
PaintballPlayer sheldon = new PaintballPlayer("Sheldon", "Lee", "Cooper");
PaintballPlayer leonard = new PaintballPlayer("Leonard", "Hofstadter");
PaintballPlayer amy = new PaintballPlayer("Amy", "Farrah", "Fowler");
System.out.println(sheldon);
System.out.println(leonard);
//Part 2 test getTotalPlayer --should be 3
System.out.println("The team has this many players " + PaintballPlayer.getTotalPlayers());
}
}
Okay my assignment is to read in from 2 separate files. The first file reads in "HallOfFameMember" and should then be stored in a vector.
The second should read in and then be stored to an array of HallOfFame
The HallOfFameMember object has 10 fields. In order firstName, lastName, deceased, month born, day born, year born, totalEarned, yearsPlayed, yearInducted, hall of fame id
The day/month/year born are all going to a separate class to create a date born. The date born is then set within HallOfFameMember. The Fields for a record will be separated by varying numbers of spaces and/or tabs (whitespaces).
After reading a record from this file, call the 10-arg constructor of HallOfFameMember, using the fields from the record as arguments in the constructor call. Add this new HallOfFameMember object to tempHallOfFameMemberVec.
The HallOfFame object has 5 fields. In order hallOfFameId, city, costToVisit, numberOfVisitorsPerYear, and name.
After reading a record from this file, call the 5-arg constructor of class HallOfFame, using the arguments obtained from the line in the file. Add this new HallOfFame object to tempHallOfFameArr.
This is all to be done from the command line.
I know that my current code will not work, I was just trying to figure out some way to do this. Vectors are completely new to me, along with BufferedReader, and I've been trying to use the examples on javapractice.com as well as a few other sites for reference. I know it will be something small that I am overlooking/missing and Ill have a duh moment when I figure it out.
At any rate my current question is this.
How do I read in from a file that has "any number of white spaces/tabs" as the delimiter. And then parse that into the appropriate fields within the appropriate class?
Giving me the code isn't gonna help, if you could just point me to a website or link that I can read to have my duh moment that would be great.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Vector;
public class HW4 {
/**
* #param args
*/
public static void main(String[] args) {
FileReader inputFileA = new FileReader("");
FileReader inputFileB = new FileReader("");
BufferedReader inputB = new BufferedReader(inputFileB);
Vector<HallOfFameMember> tempHallOfFameMemberVec = new Vector<HallOfFameMember>();
try{
BufferedReader inputA = new BufferedReader(inputFileA);
try {
String line = null;
while ((line = inputA.readLine()) != null){
}
}
}
String newHallOfFameLine = inputB.toString();
String delims = "[ \t]";
HallOfFame[] tempHallOfFameArr = newHallOfFameLine.split(delims);
for (int i = 0; i < args.length; i += 5) {
tempHallOfFameArr[i/5].setHallOfFameId(Integer.parseInt(args[i]));
tempHallOfFameArr[i/5].setCity(args[i+1]);
tempHallOfFameArr[i/5].setCostToVisit(Integer.parseInt(args[i+2]));
tempHallOfFameArr[i/5].setNumberOfVisitorsPerYear(Integer.parseInt(args[i+3]));
tempHallOfFameArr[i/5].setName(args[i+4]);
}
}
class HallOfFameMember {
private String firstName;
private String lastName;
private boolean deceased;
private int dateOfBirth;
private double totalEarned;
private int yearsPlayed;
private int yearInducted;
private int HallOfFameId;
public HallOfFameMember() {
}
public HallOfFameMember(String firstName, String lastName,
boolean deceased, int day, int month, int year, double totalEarned,
int yearsPlayed, int yearInducted, int hallOfFameId) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.deceased = deceased;
this.dateOfBirth = month + day + year;
this.totalEarned = totalEarned;
this.yearsPlayed = yearsPlayed;
this.yearInducted = yearInducted;
HallOfFameId = hallOfFameId;
}
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 boolean isDeceased() {
return deceased;
}
public void setDeceased(boolean deceased) {
this.deceased = deceased;
}
public int getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(int dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public double getTotalEarned() {
return totalEarned;
}
public void setTotalEarned(double totalEarned) {
this.totalEarned = totalEarned;
}
public int getYearsPlayed() {
return yearsPlayed;
}
public void setYearsPlayed(int yearsPlayed) {
this.yearsPlayed = yearsPlayed;
}
public int getYearInducted() {
return yearInducted;
}
public void setYearInducted(int yearInducted) {
this.yearInducted = yearInducted;
}
public int getHallOfFameId() {
return HallOfFameId;
}
public void setHallOfFameId(int hallOfFameId) {
HallOfFameId = hallOfFameId;
}
public double averageYearlySalary(double averageYearlySalary) {
return averageYearlySalary = (totalEarned / yearsPlayed);
}
}
class Date {
private int month;
private int day;
private int year;
public Date(int month, int day, int year) {
super();
this.month = month;
this.day = day;
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
class HallOfFame {
private int hallOfFameId;// ID of the hall of fame
private String name;// Name of the hall of fame
private String city;// the city in which the hall of fame is located
private double costToVisit;// cost in dollars for a visitor to a hall of
// fame for 1 day
private int numberOfVisitorsPerYear;
private static final double maxCostToVisit = 37.50;
public HallOfFame() {
}
public HallOfFame(int hallOfFameId, String name, String city,
double costToVisit, int numberOfVisitorsPerYear) {
super();
this.hallOfFameId = hallOfFameId;
this.name = name;
this.city = city;
this.costToVisit = costToVisit;
this.numberOfVisitorsPerYear = numberOfVisitorsPerYear;
}
public int getHallOfFameId() {
return hallOfFameId;
}
public void setHallOfFameId(int hallOfFameId) {
this.hallOfFameId = hallOfFameId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public double getCostToVisit() {
if (costToVisit <= maxCostToVisit) {
return costToVisit;
} else
return maxCostToVisit;
}
public void setCostToVisit(double costToVisit) {
this.costToVisit = costToVisit;
}
public int getNumberOfVisitorsPerYear() {
return numberOfVisitorsPerYear;
}
public void setNumberOfVisitorsPerYear(int numberOfVisitorsPerYear) {
this.numberOfVisitorsPerYear = numberOfVisitorsPerYear;
}
public static double getMaxcosttovisit() {
return maxCostToVisit;
}
public double totalAnnualRevenue(double totalAnnualRevenue) {
totalAnnualRevenue += costToVisit * numberOfVisitorsPerYear;
return totalAnnualRevenue;
}
}
class ReportWriter{
private Vector<HallOfFameMember> hallOfFameMemberVec;
private HallOfFame[] hallOfFameArr;
public ReportWriter() {
}
public Vector<HallOfFameMember> getHallOfFameMemberVec() {
return hallOfFameMemberVec;
}
public void setHallOfFameMemberVec(Vector<HallOfFameMember> hallOfFameMemberVec) {
this.hallOfFameMemberVec = hallOfFameMemberVec;
}
public HallOfFame[] getHallOfFameArr() {
return hallOfFameArr;
}
public void setHallOfFameArr(HallOfFame[] hallOfFameArr) {
this.hallOfFameArr = hallOfFameArr;
}
public void displayReports(){
}
}
A couple tips:
I don't want to do your homework for you, but I can't think of a quick tutorial to point you to that covers exactly what you're doing.
You're on the right track with .split, but your delimiter expression won't work for multiple spaces/tabs. Try this:
String delims = "\\s+";
That will break up your string on any consecutive sequence of one or more whitespace characters.
Also, you need to move the split up into your while loop, as well as the creation of each HallOfFameMember object. In each iteration of the loop you want to:
Split the line that you read from the file to create an array of strings representing the values for one record.
Create a new HallOfFameMember using the values from your string array. (tempHallOfFameArr[0] for first name, tempHallOfFameArr[1] for last name, etc.)
Add the new HallOfFameMember that you created to your vector
If you'd like more detail on any of these steps, I'm happy to elaborate.