The string value data member is skipped by compiler [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
string value is not displaying all though told the computer to display Please help
import java.util.Scanner;
class Author
{
private String name;
private String email;
private char gender;
public Author (String name, String email, char gender) {
this.name=name;
this.setEmail(email);
this.gender=gender;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #return the email
*/
public String getEmail() {
return email;
}
/**
* #param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* #return the gender
*/
public char getGender() {
return gender;
}
#Override
public String toString() {
return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";
}
}
class Book
{
private String Name;
Author auth;
private double price;
private int qty;
/**
* #param name
* #param auth
* #param price
*/
public Book(String name, Author auth, double price) {
super();
Name = name;
this.auth = auth;
this.price = price;
}
/**
* #param name
* #param auth
* #param price
* #param qty
*/
public Book(String name, Author auth, double price, int qty) {
super();
Name = name;
this.auth = auth;
this.price = price;
this.qty = qty;
}
public String getName() {
return Name;
}
public Author getAuth() {
return auth;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
#Override
public String toString() {
return "Book [Name=" + Name + ", auth=" + auth + ", price=" + price + ", qty=" + qty + "]";
}
}
class Student
{
private String Name;
private int roll;
date issueDate;
date returnDate;
/**
* #param name
* #param roll
* #param issueDate``
* #param returnDate
*/
public Student(String name, int roll, date issueDate, date returnDate) {
super();
Name = name;
this.roll = roll;
this.issueDate = issueDate;
this.returnDate = returnDate;
}
public String getName() {
return Name;
}
public int getRoll() {
return roll;
}
public date getIssueDate() {
return issueDate;
}
public date getReturnDate() {
return returnDate;
}
public void setReturnDate(date returnDate) {
this.returnDate = returnDate;
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
Author ahTeck=null;
System.out.println("How many Book are there in library ?");
int n=sc.nextInt();
Book []ob=new Book[n];
for(int i=0;i<n;++i)
{ System.out.println("Author's name");
String s=sc.nextLine();
sc.nextLine();
System.out.println("Author's Email Id");
String s1=sc.nextLine();
System.out.println("gender:");
char c = sc.next(".").charAt(0);
sc.nextLine();
System.out.println("Book Name:");
String b=sc.nextLine();
System.out.println("Book price:");
double price=sc.nextInt();
System.out.println("Book quantity");
int q=sc.nextInt();
ob[i]=new Book(b, new Author(s, s1, c),price,q);
System.out.println(ob[i]);
}
}
}
the question is there in
https://www.ntu.edu.sg/home/ehchua/programming/java/J3f_OOPExercises.html
Output is coming like
Book [Name=g, auth=Author [name=, email=e, gender=m], price=6.0, qty=6]
the displaying of author name is skipped

Ah yes. The ol' Scanneroo.
Right after entering the integer at the top, call sc.nextLine();
int n = sc.nextInt();
sc.nextLine();
Actually, you don't even have to call sc.nextLine() after entering a string or character. The thing is, when you enter a number, you hit the enter key as well. The Scanner class regards it as another token when you use nextInt(), so the number gets stored correctly, but the enter key \n is regarded as another token.
So when you call nextLine() after entering the number, the system sees that there is already a token remaining in the Scanner object, so it takes '\n' as its input. Thus, the name actually stores "\n", which is empty.

Related

How to output complete details

I am looking to create a leisure centre booking system in Java, which utilises OOP.
2 of the classes collect names and addresses and membership type, which are added to an ArrayList called memberRegister. How can I print all of the member details (i.e. what is stored in the array list), thus outputting Name, Address, Membertype, etc, all in one command?
My source code for classes in question follows...
public class Name {
private String firstName;
private String middleName;
private String lastName;
//constructor to create object with a first and last name
public Name(String fName, String lName) {
firstName = fName;
middleName = "";
lastName = lName;
}
//constructor to create object with first, middle and last name
//if there isn't a middle name, that parameter could be an empty String
public Name(String fName, String mName, String lName) {
firstName = fName;
middleName = mName;
lastName = lName;
}
// constructor to create name from full name
// in the format first name then space then last name
// or first name then space then middle name then space then last name
public Name (String fullName) {
int spacePos1 = fullName.indexOf(' ');
firstName = fullName.substring(0, spacePos1);
int spacePos2 = fullName.lastIndexOf(' ');
if (spacePos1 == spacePos2)
middleName = "";
else
middleName = fullName.substring(spacePos1+1, spacePos2);
lastName = fullName.substring(spacePos2 + 1);
}
// returns the first name
public String getFirstName() {return firstName; }
// returns the last name
public String getLastName() {return lastName; }
//change the last name to the value provided in the parameter
public void setLastName(String ln) {
lastName = ln;
}
//returns the first name then a space then the last name
public String getFirstAndLastName() {
return firstName + " " + lastName;
}
// returns the last name followed by a comma and a space
// then the first name
public String getLastCommaFirst() {
return lastName + ", "+ firstName;
}
public String getFullname() {
return firstName + " " + middleName + " " + lastName;
}
}
public class Address {
private String first_line, town, postcode;
public Address(String first_line, String town, String pcode)
{
this.first_line = first_line;
this.town = town;
postcode = pcode;
}
public Address()
{
first_line = "";
town = "";
postcode = "";
}
public String getFirst_line() {
return first_line;
}
public void setFirst_line(String first_line) {
this.first_line = first_line;
}
public String getTown() {
return town;
}
public void setTown() {
this.town = town;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
public class Member extends Person {
private String id; // membership ID number
private String type; // full, family, exercise, swim, casual
public Member(String id, String type, Name n, Address a)
{
super(n, a);
this.id = id;
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
import java.util.ArrayList;
public class Registration {
private ArrayList<Member> memberRegister;
public Registration()
{
memberRegister = new ArrayList();
}
public void register(Member m)
{
memberRegister.add(m);
}
public int countMembers()
{
return memberRegister.size();
}
public Member getMember(int i) {
return memberRegister.get(i);
}
public class Main {
public static void main(String[] args) {
Name n = new Name("Kieran", "David", "Nock");
Address a = new Address ("123 Skywalker Way", "London", "NW1 1AA");
Member m = new Member("001", "Full", n, a);
Registration reg = new Registration();
reg.register(m);
System.out.println(reg.countMembers());
System.out.println(reg.getMember(0).getName().getFullname());
}
}
Hey I would do it in following way
First override toString() methods of all the model classes and remember to override Member class toString() in following way
#Override
public String toString() {
return "Member{" +
"id='" + id + '\'' +
", type='" + type + '\'' +
'}'+super.toString();
}
After this adding the below single line in main method would work
reg.getMemberRegister().stream().forEach(System.out::println);
NOTE: create a getter for memberRegister list which is present in Registration Class

Creating two constructors with objects that call to other java files

I don't really know if my question makes sense but my assignment says:
"Write a third class, StudentRecord, that has two attributes:
Student stu;
Address addr;
and two constructors. The first constructor is given a Student object and an Address object to initialize the attributes. The second constructor is given a first name, a last name, a student ID, a gpa, a street address, a city, a state, and a zipcode and uses these to initialize the attributes"
I don't understand how exactly I'm supposed to make two constructors take info from two different java files.
Here's the code I have for the third class named "StudentRecord".
I have no doubt it's incorrect.
public class StudentRecord {
Student stu;
Address addr;
public StudentRecord() {
Student stu;
Address addr;
}
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
}
public String toString() {
return String.format(stu + "\n" + addr);
}
}
Here's the code I have for the TestStudentRecord class, all I get is
"null null" when I run the program.
public class TestStudentRecord {
public static void main(String[] args) {
StudentRecord stu1 = new StudentRecord("Jane", "Brown", 182765, 2.333, "13 Flower St.", "Pulteneyville", "NY", 14386);
System.out.println(stu1);
}
}
All I get is "null null" when I run the program instead of the toString method giving me the student info I have typed into the test class.
For those asking for the Student and Address classes, here you go:
public class Student {
// attributes of a Student
private String firstName;
private String lastName;
private int studentId;
private double gpa;
/**
* Student constructor.
* #param _fName student's first name
* #param _lName student's last name
* #param _id student's id number
* #param _gpa students GPA
*/
public Student(String _fName, String _lName, int _id, double _gpa) {
firstName = _fName;
lastName = _lName;
studentId = _id;
gpa = _gpa;
}
/**
* getFirstName - Accessor for first name
* #return the student's first name
*/
public String getFirstName() {
return firstName;
}
/**
* getLastName - Accessor for last name
* #return the student's last name
*/
public String getLastName() {
return lastName;
}
/**
* getId - Accessor for ID
* #return the student's ID
*/
public int getStudentId() {
return studentId;
}
/**
* getGpa - Accessor for gpa
* #return the student's gpa
*/
public double getGpa() {
return gpa;
}
/**
* setFirstName - Mutator for first name
* #param the new first name
*/
public void setFirstName(String _fName) {
firstName = _fName;
}
/**
* setLastName - Mutator for last name
* #param the new last name
*/
public void setLastName(String _lastName) {
lastName = _lastName;
}
/**
* setStudentId - Mutator for ID
* #param the new ID
*/
public void setStudentId(int _id) {
studentId = _id;
}
/**
* setGpa - Mutator for gpa
* #param the new gpa
*/
public void setGpa(double _gpa) {
gpa = _gpa;
}
// toString Method
public String toString() {
return String.format(getLastName() + ", " + getFirstName() + "\n" + "ID: " + getStudentId() + " GPA: %3.1f", getGpa());
}
}
public class Address {
private String street;
private String city;
private String state;
private int zip;
public Address(String _street, String _city, String _state, int _zip) {
street = _street;
city = _city;
state = _state;
zip = _zip;
}
// Accessors
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public int getZip() {
return zip;
}
// Mutators
public void setStreet(String _street) {
street = _street;
}
public void setCity(String _city) {
city = _city;
}
public void setState(String _state) {
state = _state;
}
public void setZip(int _zip) {
zip = _zip;
}
// toString Method
public String toString() {
return String.format(getStreet() + "\n" + getCity() + ", " + getState() + " " + getZip());
}
}
would suggest you to please follow below approach to initialize your object through argumented construtor.
public class StudentRecord {
Student stu;
Address addr;
public StudentRecord() {
Student stu;
Address addr;
}
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
this.stu = new Student(_fName, _lName, _id, _gpa);
this.addr=new Address(_street,_city,_state,_zip);
}
public String toString() {
return String.format(stu + "\n" + addr);
}
}
As you have already overided toString method in address and student class so you will get the object.
Your constructor is like below. Empty Constructor will not assign values to your class variables.
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
}
it should be like below as mentioned by Eran.
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
this.stu = new Student(_fName, _lName, _id, _gp);
this.addr = new Address(_street, _city, _state, _zip);
}
Now your toString will have the values for stu and addr. Which will get printed.
You have to initilize the variables with this.{variable name} = {variable name}.
Also it is often better to chain the Constructors (see How do I call one constructor from another in Java?), in this way changes in classes, with many constructors, are way easier to implement.
I would also suggsest to rename your variables, because in Java they should not start with an underscore (see https://www.javatpoint.com/java-naming-conventions).
public class StudentRecord {
Student student;
Address addr;
public StudentRecord(Student student, Address addr) {
this.student = student;
this.addr = addr;
}
public StudentRecord(String fName, String lName, int id, double gpa, String street, String city, String state, int zip){
this(new Student(fName, lName, id, gpa),
new Address(street,city,state,zip));
}
public String toString() {
return String.format(student + "\n" + addr);
}
}

Java Eclipse: My code's output is skipping a line and I don't know why [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
The title says it all. This is a basic Customer class that the user inputs their name/age/street address/city/state/zip code and then the program formats the input and returns it to the user. When I run this class it skips over the 'Street Address' and goes straight to 'City' and thus I can't get it to let me input my street address.
I've looked at a fairly similar issue in this thread here: Java is skipping a line (Strings in a Scanner ??)
However I haven't derived anything from that that has helped me solve this issue. I'm sure its extremely basic but I'm just unable to catch it and don't have much time to work on this today, so any tips/help are appreciated!
public class Customer {
String name;
String streetAddress;
String city;
String state;
String zip;
int age;
//default constructor
public Customer() {
name = "Unknown";
streetAddress = "Unknown";
city = "Unknown";
state = "Unknown";
zip = "Unknown";
age = 0;
}
//constructor to accept values for the above attributes
public Customer(String n, String sAdd, String c, String st8, String z, int a) {
name = n;
streetAddress = sAdd;
city = c;
state = st8;
zip = z;
age = a;
}
//getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String displayAddress() { //returns a string with the complete formatted address
String showAddress;
showAddress = ("\nStreet Address: " + streetAddress + "\nCity: " + city + "\nState: " + state + "\nZip Code: " + zip);
return showAddress;
}
public String displayAddressLabel() { //returns a string with the customers name/age
String nameAgeAddress;
nameAgeAddress = ("Name: " + name + "\nAge: " + age);
return nameAgeAddress;
}
//main method
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//creating an object of the Customer class
Customer actualCustomer = new Customer();
//getting info for displayAddressLabel() and displayAddress
System.out.println("Enter your name: ");
actualCustomer.setName(scan.nextLine());
System.out.println("Enter your age: ");
actualCustomer.setAge(scan.nextInt());
//issue is here
System.out.println("Enter your street address: ");
actualCustomer.setStreetAddress(scan.nextLine());
System.out.println("Enter the city you live in: ");
actualCustomer.setCity(scan.nextLine());
System.out.println("Enter the state you live in: ");
actualCustomer.setState(scan.nextLine());
System.out.println("Enter your zip code: ");
actualCustomer.setZip(scan.nextLine());
System.out.println(actualCustomer.displayAddressLabel());
System.out.println(actualCustomer.displayAddress());
}
}
After this line:
actualCustomer.setAge(scan.nextInt());
you should call:
scan.nextLine();
because after scan.nextInt() there is a new line character left to be read (after inputting int you press Enter to confirm your input and you're missing to read it from your Scanner). Instead of writing these two lines:
actualCustomer.setAge(scan.nextInt());
scan.nextLine();
You might want to change it to:
actualCustomer.setAge(Integer.parseInt(scan.nextLine()));
It will get rid of new line character.

How to add multiple students to student class?

Im trying to create a student class, a course class and the main class. I am trying to add students to the course, and when students are added to the class the number of students in the course should increase, when the the code is run it should print the course details followed by the students in the course.
I have got the following code:
Main class:
public class JavaLecture3 {
public static final int DEBUG = 0;
public static void main(String [] args){
//Student student = new Student(); // Calling default constructor here.
Course course = new Course();
student = new Student(21, "Joe", "CSE", "07447832342");
course = new Course("CSE", "Tom", 5);
System.out.println("Course Information: ");
System.out.println("-------------------");
System.out.println(course);
System.out.println();
System.out.println("Student contains: "); // calls student.toString());
System.out.println("-------------------");
System.out.println(student);
}
}
Course class:
public class Course {
ArrayList<Student> studentList;
private String courseName;
private String teacher;
private int noOfStudents;
//Getters
public String getCourseName(){
return this.courseName;
}
public int getNoOfStudents(){
return this.noOfStudents;
}
public String getTeacher(){
return this.teacher;
}
//Setters
public void setCourseName(String courseName){
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents){
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher){
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with defaults
*
*/
public Course(){
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
studentList = new ArrayList<Student>();
}
/**
* Constructor with parameters
* #param noOfStudents integer
* #param courseName String with the Course name
* #param teacher String with the teacher
*/
public Course(String courseName, String teacher, int noOfStudents){
this.courseName = courseName;
this.teacher = teacher;
noOfStudents = noOfStudents;
studentList = new ArrayList<Student>();
}
public static void addStudent(Student newStudent){
if(studentList.size()==noOfStudents){
System.out.println("The class is full, you cannot enrol.");
}
else {
studentList.add(newStudent);
}
}
public String toString() {
return "Course Name: " + this.courseName + " Teacher: " + this.teacher
+ " Number of Students: " + this.noOfStudents;
}
}
Student class:
public class Student {
private String name;
private int age;
public String gender = "na";
private String course;
private String phoneNo;
public static int instances = 0;
// Getters
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
public String getCourse(){
return this.course;
}
public String getPhoneNo(){
return this.phoneNo;
}
// Setters
public void setAge(int age){
this.age = age;
}
public void setName(String name){
if (JavaLecture3.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
public void setCourse(String course){
this.course = course;
}
public void setPhoneNo(String phoneNo){
this.phoneNo = phoneNo;
}
/**
* 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";
this.course = "Not Set";
this.phoneNo = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
* #param course String with course name
* #param phoneNo String with phone number
*/
public Student(int age, String name, String course, String phoneNo){
this.age = age;
this.name = name;
this.course = course;
this.phoneNo = phoneNo;
}
/**
* Gender constructor
* #param gender
*/
public Student(String gender){
this(); // Must be the first line!
this.gender = gender;
}
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 + " Course: " + this.course + " Phone number: "
+ this.phoneNo;
}
}
Reference:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html?is-external=true
Course.getNoOfStudents should just return studentList.size(). No need to maintain a separate variable.
To print a list of students (from Course):
for(int i=0;i<studentList.size();i++) System.out.println(studentList.get(i));
Since you initialized the array list in the Course class, you should add the students to it. You should create a method in Course that adds an object to the array list such as:
public void addStudent(Student s){
studentList.add(s);
noOfStudents++;
}
To add multiple students:
public void addStudents(Student[] students){
for(int i = 0; i < students.length; i++){
studentList.add(students[i]);
}
}
You're almost there, just use the .add method made for you in the array list.
public class JavaLecture3 {
public static final int DEBUG = 0;
public static void main(String [] args){
Student student = new Student(); // Calling default constructor here.
Course course = new Course();
student = new Student(21, "Joe", "CSE", "07447832342");
course = new Course("CSE", "Tom", 5);
course.addStudent(student);
System.out.println("Course Information: ");
System.out.println("-------------------");
System.out.println(course);
System.out.println();
System.out.println("Student contains: "); // calls student.toString());
System.out.println("-------------------");
System.out.println(student);
}
}
public class Course {
List<Student> studentList;
private String courseName;
private String teacher;
private int noOfStudents;
// Getters
public String getCourseName() {
return this.courseName;
}
public int getNoOfStudents() {
return this.noOfStudents;
}
public String getTeacher() {
return this.teacher;
}
// Setters
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents) {
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with
* defaults
*
*/
public Course() {
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
studentList = new ArrayList<Student>();
}
/**
* Constructor with parameters
*
* #param noOfStudents
* integer
* #param courseName
* String with the Course name
* #param teacher
* String with the teacher
*/
public Course(String courseName, String teacher, int noOfStudents) {
this.courseName = courseName;
this.teacher = teacher;
this.noOfStudents = noOfStudents;
studentList = new ArrayList<Student>();
}
public void addStudent(Student newStudent) {
if (studentList.size() == noOfStudents) {
System.out.println("The class is full, you cannot enrol.");
} else {
studentList.add(newStudent);
}
}
#Override
public String toString() {
return "Course Name: " + this.courseName + " Teacher: " + this.teacher
+ " Number of Students: " + studentList.size();
}
}
public class Student {
private String name;
private int age;
public String gender = "na";
private String course;
private String phoneNo;
public static int instances = 0;
// Getters
public int getAge() {
return this.age;
}
public String getName() {
return this.name;
}
public String getCourse() {
return this.course;
}
public String getPhoneNo() {
return this.phoneNo;
}
// Setters
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
if (JavaLecture3.DEBUG > 3)
System.out.println("In Student.setName. Name = " + name);
this.name = name;
}
public void setCourse(String course) {
this.course = course;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
/**
* 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";
this.course = "Not Set";
this.phoneNo = "Not Set";
}
/**
* Constructor with parameters
*
* #param age
* integer
* #param name
* String with the name
* #param course
* String with course name
* #param phoneNo
* String with phone number
*/
public Student(int age, String name, String course, String phoneNo) {
this.age = age;
this.name = name;
this.course = course;
this.phoneNo = phoneNo;
}
/**
* Gender constructor
*
* #param gender
*/
public Student(String gender) {
this(); // Must be the first line!
this.gender = gender;
}
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 + " Course: " + this.course + " Phone number: "
+ this.phoneNo;
}
}
public class JavaLecture3 {
public static final int DEBUG = 0;
public static void main(String [] args){
//Create course object
Course course = new Course("CSE", "Tom", 5);
Scanner scanner = new Scanner(System.in);
String cmd = "Yes";
while(cmd.equals("Yes")){
Student student = new Student();
System.out.print("Enter a new student? ");
cmd = scanner.next();
if (cmd.equals("Yes")){
//Read student name
System.out.print("Enter a student name: ");
String name = scanner.next();
student.setName(name);
//Read student Age
System.out.print("Enter a student age: ");
int age = scanner.nextInt();
student.setAge(age);
//Read student Course
System.out.print("Enter a student course: ");
String stdent_course = scanner.next();
student.setCourse(stdent_course);
//register the student to the class
course.addStudent(student);
}
}
scanner.close();
System.out.println("Course Information: ");
System.out.println("-------------------");
System.out.println(course.toString());
System.out.println();
}
}
I reworked a bit your toString() method from Course class. This should print the list of students attending a class.
public String toString (){
String ret_value = "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender + " Course: " + this.course + " Phone number: "
+ this.phoneNo + " Students attending this course:";
for (Student student: studentList) {
ret_value = ret_value + " " + Student.getName();
}
return ret_value;
}

error cannot find symbol - variable

I am new to using Java - so please forgive my ignorance. Would you be able to look at this code and let me know why I get error:
cannot find symbol - variable
when I call the constructor method. I am using BlueJ. Basically I put in the variables and then hit ok to create an object but it comes up with that error.
/**
* Write a description of class Membership here.
*
* #author (Gohar Warraich)
* #version (1.0)
*/
public class Membership
{
// instance variables - replace the example below with your own
private String firstname;
private String lastname;
private String phonenumber;
private int idnumber;
/**
* Constructor for objects of class Membership
*/
public Membership(String newfirstname, String newlastname, String newphonenumber, int newidnumber)
{
// initialise instance variables
firstname = newfirstname;
lastname = newlastname;
phonenumber = newphonenumber;
idnumber = newidnumber;
}
/**
* Accessor method of Membership
*/
public String getfirstname()
{
return firstname;
}
public String getlastname()
{
return lastname;
}
public String getphonenumber()
{
return phonenumber;
}
public int getidnumber()
{
return idnumber;
}
/**
* Mutator method of Membership
*/
public void setfirstname(String insertfirstname)
{
firstname = insertfirstname;
}
public void setlastname(String insertlastname)
{
lastname = insertlastname;
}
public void setphonenumber(String insertphonenumber)
{
phonenumber = insertphonenumber;
}
public void setid(int insertidnumber)
{
idnumber = insertidnumber;
}
public void printMembership()
{
System.out.println("The firstname is " + firstname + " The lastname is " + lastname +" The phoneNumber is "+ phonenumber +" The idNumber is " +idnumber);
}
}
#gohar, There isn't a problem in this code. It must be in your call to the constructor. I'll give you an example of what this should look like.
Membership membershipName = new Membership ("String", "String", "String", 0101)
0101 can be any int, and you can name the variable what ever you want by changing membershipName. Hope this helps. :)

Categories