The error I am reviving is "void type is not allowed here " how would I fix this error in order to print out my array list.
import java.util.ArrayList;
public class Library
{
private ArrayList<Member>listOfMembers;
public Library()
{
listOfMembers = new ArrayList<Member>();
}
public void storeMember(Member Member)
{
listOfMembers.add(Member);
}
public int numberOfMembers()
{
return listOfMembers.size();
}
public void listMembers()
{
for (int item=0; item<listOfMembers.size(); item++ ) {
Member m = listOfMembers.get (item);
System.out.println(m.GetWholeName());
}
}
}
and here is my member class just in case you need it
class Member
{
// The fields.
private String firstname;
private String lastname;
private Integer number;
private Integer id;
/**
hehe
*/
public Member(String firstName, String lastName, Integer telNumber, Integer memberId)
{
firstname = firstName;
lastname = lastName;
number = telNumber;
id = memberId;
}
// Add the methods here ...
public void GetWholeName(){
System.out.println(firstname + (" ") + lastname);
}
}
I'm trying to print the first and last name of my member class by using an array list in my library class
You are trying to print out the result of m.GetWholeName() which returns void. Change GetWholeName to return a String instead, or simply call GetWholeName as it's already printing the name to standard out although that behavior doesn't quite match up to the behavior the name would imply.
public String GetWholeName() {
return firstname + " " + lastname;
}
In Member class change this:
System.out.println(firstname + (" ") + lastname);
to this:
return firstname + " " + lastname;
Related
Inheritance is not completely working for me as the extra variables outside the inheritance class are not being displayed. When I input the employee details and input the wage it is accepted. But then it is not shown when I list all employees in database or when searching for an employee
public class Employee extends Person {
public Employee(){ }
public Employee (int id, int wage, String name, String surname){
super(id,name,surname);
this.wage = wage;
}
private int wage;
public void SetWage(int wg){
wage=wg;
}
public int GetWage (){
return wage;
}
public String toString(){
return "ID: " + this.GetId() + "\n"
+ "Name:" + this.GetName() + "\n"
+ "Surname:" + this.GetSurname() + "\n"
+ "Wage: " + this.GetWage();
}
}
Similarly the client class is not working. Also here is the code for the person class
public class Person{
public Person(){
pId = 0;
pName = "";
pSurname = "";
}
public Person (int id, String nm, String sn) {
pId = id;
pName = nm;
pSurname = sn;
}
private int pId;
private String pName;
private String pSurname;
public int GetId(){
return pId;
}
public void SetId(int id){
pId= id;
}
public String GetName(){
return pName;
}
public void SetName(String nm){
pName = nm;
}
public String GetSurname (){
return pSurname;
}
public void SetSurname(String sn){
pSurname = sn ;
}
public String ToString(){
return "ID: " + this.GetId() + "\n"
+ "Name:" + this.GetName() + "\n"
+ "Surname:" + this.GetSurname();
}
}
Any suggestions?
First of all, order your class as follows: fields, constructors, methods. Try not to have constructors before the fields, it's rather hard to read.
Also, just like paisanco noted out in the comments - try to ask more specific questions, it's not easy to understand what is the problem.
Last thing - if I understand right, you probably can't access Person class fields, such as:
private int pId;
private String pName;
private String pSurname;
This is most likely problem of how you create your object.
Instead of
Emplyee emp = new Employee();
Try creating employee object in such manner:
Person pers = new Employee();
This should fix this and you should be able to access person class fields aswell.
And if you after that would like to access employee fields like wage and so on, you should cast the object to Employee object, e.g:
if (pers instanceof Employee) {
((Employee) pers).getWage();
}
If you are trying to use it in the following way:
Person employee = new Employee()
you will not be able to use SetWage and GetWage functions because they are not part of Person object. If you want to use work that way you can declare them as abstract functions in Person class of instantiate your object differently: Employee employee = new Employee()
The details in this example isn't that important just trying to figure out how I can solve this, I have 3 separate classes Person , Interests and Location. all are objects, a person would have an list of interests and each interest will have a list of locations, i'm using a toString to print my person object and the interest but I can't figure out how to print out the locations of each interest. Do i need to overload my toString?
public class Person{
private String name;
private ArrayList<Interest> interests = new ArrayList<Interest>();
public Person(String name, ArrayList<Interest> interests) {
this.name = name;
this.interests = interests;
}
public void addInterest(Interest newInterest) {
interests.add(newInterest);
}
public Interest getInterest(int indexOfInterest) {
return interests.get(indexOfInterest);
}
public ArrayList<Interest> getInterests() {
return interests;
}
public String getName() {
return name;
}
public String toString() {
String result = getName() + " ";
for(Interest interest : interests) {
result += interest.getName() + "(" + interest.getDangerRating() + ")" + " ";
}
return result.trim();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Interest {
private int dangerRating;
private String name;
private ArrayList<Location> location = new ArrayList<Location>();
public Interest (int dangerRating, String name, ArrayList<Location> location) {
this.dangerRating = dangerRating;
this.name = name;
this.location = location;
}
public int getDangerRating() {
return dangerRating;
}
public String getName() {
return name;
}
}
////////////////////////////////////////////////////////////////
public class Location {
private String location;
public Location (String location){
this.location = location;
}
public String getLocation() {
return location;
}
}
I reccomend making a toString for each class. That way you can call a Location toString in the Intrest's toString, then the location toString in the Person. Also, the ArrayList class has its own toString that prints all the items in the array.
Currently you only have one toString and you are manualy getting the data for each. So for example:
(In the Location Class):
#Override
public String toString()
{
return "Location: " + location;
}
(In the Interest Class):
#Override
public String toString()
{
return "Danger Rating: " + dangerRating +
"Name: " + name +
"Location: " location.toString(); //Note, the name location is confusing here since it is an ARRAYLIST of locations.
}
(In the Person Class):
#Override
public String toString()
{
return "Name: " + name +
"Intrests: " + intrests.toString();
}
(In the Main Class):
public static void main(String[] args)
{
Intrest[] intrests = new Intrest[4]; //TODO: Create intrests, currently they are all null.
Person thePerson = new Person("Eddie", intrests);
System.out.println("Person Info: " + thePerson.toString());
}
Learn to use your tools: every IDE can generate an overriden toString() method and they are good for the most cases.
public class Location {
// ...
#Override
public String toString() {
return "Location{" +
"location='" + location + '\'' +
'}';
}
}
public class Interest {
// ...
#Override
public String toString() {
return "Interest{" +
"dangerRating=" + dangerRating +
", name='" + name + '\'' +
", location=" + location +
'}';
}
}
class Person{
// ...
#Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", interests=" + interests +
'}';
}
}
I would advise you to stick to your IDE's default toString()s, because that will make your toString()'s look consistent acros all your projects, and soon they will be familiar for you and easy to read.
In your Person class, you call interest.toString() in a loop for all interests
public String toString() {
String result = getName() + " ";
for(Interest interest : interests) {
// add this function to print interest stuff
result += interest.toString();
}
return result.trim();
}
In your Interest class, you'll want a toString or similar method like so
public String toString(){
String s = "";
//print stuff for interest i.e. s+= what you want to add
//loop through locations associated with Interest
for(Location l : this.location ){
// print what you want in location.toString()
// add this funciton to your Location class
s += l.toString()
}
return s;
}
And then in your Main you just need to call
person.toString() and it will loop through and print everything for you.
Sorry, I am very new to programming for university. This is a practise question for our test and is set up on code runner. The entire main method and all the classes, methods, constructors and variables were already give to me and I have to make the shown class to print out what I have written. But Bride.getAge() and Location.getSuburb() in the println will not work. Do I need to add something else in?
public class Location {
public static void main(String[] args) {
Bride person = new Bride("Amy Cronos", 29);
Location place = new Location("Tonsley", "South Rd");
Wedding wed = new Wedding(person,place);
show(wed);
}
public static void show(Wedding wed){
System.out.println("Wedding data:" );
System.out.println("Bride: " + wed.getBride() + ", age: " + Bride.getAge);
System.out.println("Location: " + wed.getPlace() + ", suburb: " + Location.getSuburb());
}
private String suburb;
private String street;
Location(String suburb, String street){
this.suburb = suburb;
this.street = street;
}
public String getSuburb(){
return suburb;
}
public String getStreet(){
return street;
}
public class Bride {
private String name;
private int age;
Bride(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
public class Wedding {
private Bride person;
private Location place;
Wedding(Bride person, Location place){
this.person = person;
this.place = place;
}
public Bride getPerson(){
return person;
}
public Location getPlace(){
return place;
}
}
}
You need to correct the below lines in show method
System.out.println("Bride: " + wed.getBride() + ", age: " + wed.getPerson().getAge());
System.out.println("Location: " + wed.getPlace() + ", suburb: " + wed.getPlace().getSuburb());
Since you are using Class names with methods, Bride.getAge() and Location.getSuburb(), these methods are considered static. Hence the error. Since these are not static methods, you need to use the objects of the class to access them rather than Class names.
you have passed object of class Bride and Location so you need to get value like below code : Try with below code and try to understands object in java , static is different thing .
public static void show(Wedding wed){
System.out.println("Wedding data:" );
System.out.println("Bride: " + wed.getPerson() + ", age: " + wed.getPerson().getAge());
System.out.println("Location: " + wed.getPlace() + ", suburb: " + wed.getPlace().getSuburb());
}
My program is supposed to store the info submitted by the users into another class. It is then supposed to perform a small calculation to determine age. The final part is to create an instance of the secondary class in the Driver and then print out all the info using toString. My results are null, null, 0 ,0 everytime. What am I doing wrong?
public class CustomerInfoProgram {
public static Scanner scan = new Scanner(System.in);
public static String firstName;
public static String lastName;
public static String address;
public static String phoneNumber;
public static int dob;
public static int currentYear;
public static int age;
public static String name;
public static void main(String[] args) {
Customer in = new Customer();
getCustomerName();
getPhone();
getAddress();
getDOB();
getCurrentYear();
in.toString();
}
public static String getCustomerName() {
System.out.println("What is your first name?");
firstName = scan.nextLine();
System.out.println("What is your last name?");
lastName = scan.nextLine();
name = firstName + " " + lastName;
return name;
}
public static String getAddress() {
System.out.println("What is your address?");
address = scan.nextLine();
return address;
}
public static String getPhone() {
System.out.println("What is your phone number?");
phoneNumber = scan.nextLine();
return phoneNumber;
}
public static int getDOB() {
System.out.println("What year were you born?");
dob = scan.nextInt();
return dob;
}
public static int getCurrentYear() {
System.out.println("What is the current year?");
currentYear = scan.nextInt();
return currentYear;
}
}
Secondary class:
import java.util.Scanner;
public class Customer {
public static int age;
public static String allInfo;
public static String name = CustomerInfoProgram.name;
public static String address = CustomerInfoProgram.address;
public static String phoneNumber = CustomerInfoProgram.phoneNumber;
public static int dob = CustomerInfoProgram.dob;
public static int currentYear = CustomerInfoProgram.currentYear;
private int getAge() {
age = (currentYear - dob);
return age;
}
public String toString() {
getAge();
allInfo = (name + " " + address + " " + phoneNumber + " " + dob + " " + age);
System.out.println(allInfo);
return toString();
}
}
public static String name = CustomerInfoProgram.name;
This only sets the value of CustomerInfoProgram.name when the field is initialized, i.e. once, when the Customer class is loaded - it does not update when CustomerInfoProgram.name is updated.
The Customer class is (at the latest) loaded when you call new Customer(), which happens before you run any methods to set the value of CustomerInfoProgram.name, so it is null when you attempt to use name.
If you want to use the current value of CustomerInfoProgram.name, just refer to that field directly. Alternatively, you can add a getter, which will return its current value:
public static String getName() {
return CustomerInfoProgram.name;
}
then call the getter in place of name:
allInfo = (getName() + " " + ...
(Exactly the same applies to the other fields).
You also will get a StackOverflowError from you toString() method:
public String toString() {
getAge();
allInfo = (name + " " + address + " " + phoneNumber + " " + dob + " " + age);
System.out.println(allInfo);
return toString();
}
You are unconditionally calling toString() inside toString(), so this will just keep calling itself until it runs out of stack space.
Instead, just return allInfo:
public String toString() {
getAge(); // This actually does nothing - do you intend to use it in the return value?
return (name + " " + address + " " + phoneNumber + " " + dob + " " + age);
}
and call System.out.println in your main method:
System.out.println(in); // Implicitly calls toString().
See #Andy's answer for the cause of your problem.
The usual approach to this would be to collect the values to be stored in your Customer object before you create it, then use a nondefault constructor call. A partial example might look like this:
// get individual values here
getCustomerName();
getPhone();
// etcetera
Customer in = new Customer(name, phone, address, dob);
The rest I leave as an exercise for the reader.
Being static attributes the initialization in both the classes would be only once. So post you get the input from user those values are not set to the attributes. Hence the null.
I'm working on a class assignment that accepts last name, first name and score for one or more students, stores them in an array and then sorts alphabetically by last name (or first name if last name is the same).
We're required to use a Student class that implements the Comparable interface.
As soon as I get to the Arrays.sort portion of the code, I get a ClassCastException stating that "Student cannot be cast to java.lang.Comparable".
I've searched and reviewed, tried to use implements Comparable<Student>, Clean and Build, but the error persists. Any help or hints are appreciated.
the error:
Exception in thread "main" java.lang.ClassCastException:
studentscoreapp.Student cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.sort(Arrays.java:1079)
at studentscoreapp.StudentScoreApp.main(StudentScoreApp.java:35)
Java Result: 1 BUILD SUCCESSFUL (total time: 12 seconds)
Here's my Student class:
public class Student implements Comparable
{
private String lastName;
private String firstName;
private int score;
public Student(String fName, String lName, int s)
{
fName = firstName;
lName = lastName;
s = score;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public int getScore()
{
return score;
}
public void setScore(int score)
{
this.score = score;
}
#Override
public int compareTo(Object obj)
{
Student sent = (Student) obj;
if (sent.lastName.equals(this.lastName))
{
return this.firstName.compareToIgnoreCase(sent.firstName);
}
else return this.lastName.compareToIgnoreCase(sent.lastName);
}
#Override
public String toString()
{
return lastName + firstName + score;
}
}
the Comparable interface:
public interface Comparable
{
int compareTo(Object obj);
}
and my main:
import java.util.Arrays;
public class StudentScoreApp
{
public static void main(String[] args)
{
String firstName;
String lastName;
int score;
System.out.println("Welcome to the Student Scores Application");
int numStudents = Validation.getInt("Enter # of Students: ");
Student[] studentArray = new Student[numStudents];
int i;
for (i = 0; i < numStudents; i++)
{
firstName = Validation.getString("Student [" + (i + 1) + "] first name: ");
lastName = Validation.getString("Student [" + (i + 1) + "] last name: ");
score = Validation.getInt("Student [" + (i + 1) + "] score: ", 0, 100);
studentArray[i] = new Student(firstName, lastName, score);
}
Arrays.sort(studentArray); //line 35
System.out.println();
//take each obj of the array and print the student info
for (Student obj : studentArray)
{
System.out.println(obj.toString());
}
}
}
Arrays.sort() accepts an array of objects which are subtypes of java.lang.Comparable. In your code, you have created your own Comparable interface, which, while it behaves the same way as java.lang.Comparable, is not the same interface.