How can I print the Students info? - java

Is there a way I can print my students with the information provided?
I created a service class with all the information about the course, where I wish to input my students info on a very simple way.
student class:
public class student {
//Fields
private static String classNumber = "264";
private static String className = "Transfiguration";
private static String instructor = "Professor McGonagall";
private int studentId;
private String firstname;
private String lastname;
private String address;
private String city;
private String state;
private String email;
//Getters and setters
static String getClassNumber(){
return (classNumber);
}
static String getClassName(){
return (className);
}
static String getInstructor(){
return (instructor);
}
static void setClassName(String name){
className = name;
}
int getStudentId(){
return (studentId);
}
String getFirstName(){
return (firstname);
}
String getLastName(){
return (lastname);
}
String getAddress(){
return (address);
}
String getCity(){
return (city);
}
String getState(){
return (state);
}
String getEmail(){
return (email);
}
void setFirstName(String first) {
this.firstname = first;
}
void setLastName(String last) {
this.lastname = last;
}
void setAddress(String rua) {
this.address = rua;
}
void setCity(String cidade) {
this.city = cidade;
}
void setEmail(Sring correio) {
this.email = correio;
}
//Contructors
student(String la) {
this.firstname = first;
this.lastname = last;
this.studentId += 1000;
}
student(String la, int id, String first, String last, String rua, String cidade, String correio) {
this(la);
this.address = rua;
this.city = cidade;
this.email = correio;
}
public String toString() {
String data = "Course: " + classNumber + " " + className +
"\t instructor: " + instructor +
"\t Student Number: " + id +
"\t Student Name: " + firstname + " " + lastname +
"\t Address: " + rua + cidade +
"\t Email: " + correio;
return (data);
}
}
studentTest class:
public class studentTest {
public static void main (String [] args) {
System.out.println("Course: " + student.getClassNumber() + student.getClassName());
student a = new student("Kakashi", "Hatake", "W 69th st", "NY", "khsensei#ninja.com");
student b = new student("Albus", "Dumbledore", "W 116th st", "NY", "princip-al#hogwarts.com" );
student c = new student("Hyuk", "Jang", "321 Maple St", "NJ", "jh#actors.com");
student d = new student("Michael", "Jackson", "543 thriller st", "NY", "mj#singer.com");
student e = new student("Hamilton", "Alexander", "E 86th st", "NY", "justyouwait#broadway.com");
String fname = a.firstname;
System.out.println("First Name: " + fname);
System.out.println(a.toString());
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
}
}
What I wish to do is print all the information on their proper place, however I must have forgotten something pretty serious that I'm getting error messages. Are the students info linked properly to the first class?
--
A few of the error messages I get:
"student.java:114: error: class studentTest is public, should be declared in a file named studentTest.java" - for this one, I've tried before and I can put both classes on the same file, why wouldn't be working now?
Some symbols can't be found:
symbol: variable first
location: class student
student.java:83: error: cannot find symbol
this.lastname = last;
the same also happens with the variables id, last, rua, cidade, and correio.
there's also an error about the constructor
constructor student.student(String) is no applicable
(actual and formal argument lists differ in length)
constructor student.student(String, int, String, String, String, String) is no applicable
student.java:124 error: no suitable constructor found for student (String, String...)

The problem in the code is in this line:
String fname = a.firstname;
You are basically trying to access a private field when you actually want to do is:
String fname = a.getFirstName();
The other problem is the constructor:
student(String la) {
this.firstname = first;
this.lastname = last;
this.studentId += 1000;
}
both first and last variables do not exist in this context.

I've added comments to better point out where the errors are that the compiler is complaining about. These are all very common compiler messages so you should take the time to understand what they are referring to and fix them. You will see them over and over again.
public class student { //class names start with an uppercase letter
//Fields
private static String classNumber = "264";
private static String className = "Transfiguration";
private static String instructor = "Professor McGonagall";
private int studentId;
private String firstname;
private String lastname;
private String address;
private String city;
private String state;
private String email;
//Getters and setters
static String getClassNumber(){
return (classNumber);
}
static String getClassName(){
return (className);
}
static String getInstructor(){
return (instructor);
}
static void setClassName(String name){
className = name;
}
int getStudentId(){
return (studentId);
}
String getFirstName(){
return (firstname);
}
String getLastName(){
return (lastname);
}
String getAddress(){
return (address);
}
String getCity(){
return (city);
}
String getState(){
return (state);
}
String getEmail(){
return (email);
}
void setFirstName(String first) {
this.firstname = first;
}
void setLastName(String last) {
this.lastname = last;
}
void setAddress(String rua) {
this.address = rua;
}
void setCity(String cidade) {
this.city = cidade;
}
void setEmail(Sring correio) { //You misspelled the type of the parameter
this.email = correio;
}
//Contructors
student(String la) {
this.firstname = first; //The parameter list to this constructor
//only contains 'la', 'first' does not exist
this.lastname = last; //The parameter list to this constructor
//only contains 'la', 'last' does not exist
this.studentId += 1000;
}
student(String la, int id, String first, String last, String rua, String cidade, String correio) {
this(la);
this.address = rua;
this.city = cidade;
this.email = correio;
}
public String toString() {
String data = "Course: " + classNumber + " " + className +
"\t instructor: " + instructor +
"\t Student Number: " + id + //id is the parameter in the
//constructor, not the private field name
"\t Student Name: " + firstname + " " + lastname +
"\t Address: " + rua + cidade + //rua and cidade are parameters in the
//constructor, not the private field names
"\t Email: " + correio; //correio is the parameter in the
//constructor, not the private field name
return (data);
}
}
studentTest class:
public class studentTest { //classes start with a capital letter and belong in seprate files
public static void main (String [] args) {
System.out.println("Course: " + student.getClassNumber() + student.getClassName());
//Student's constructor requires 7 arguments of type String, int, String, String, String, String, String
student a = new student("Kakashi", "Hatake", "W 69th st", "NY", "khsensei#ninja.com");
student b = new student("Albus", "Dumbledore", "W 116th st", "NY", "princip-al#hogwarts.com" );
student c = new student("Hyuk", "Jang", "321 Maple St", "NJ", "jh#actors.com");
student d = new student("Michael", "Jackson", "543 thriller st", "NY", "mj#singer.com");
student e = new student("Hamilton", "Alexander", "E 86th st", "NY", "justyouwait#broadway.com");
String fname = a.firstname; //firstname is a private field
System.out.println("First Name: " + fname);
System.out.println(a.toString());
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
}
}

Related

I am trying to print out the Address a1 of an object person p1 I created. The Person constructor takes in the Address object as well

public class Person {
enum Sex{Male, Female}
private String initials;
private String lastname;
private String firstname;
private Sex sex;
private int yearOfBirth;
private double netWorth;
private Address homeaddress;
Sex male = Sex.Male;
Sex female = Sex.Female;
public Person(){}
public Person(String firstname, String lastname, int yearOfBirth, Sex sex, double netWorth, Address homeaddress)
{
this.netWorth = netWorth;
this.firstname = firstname;
this.lastname = lastname;
this.sex = sex;
this.homeaddress = homeaddress;
this.male = Sex.Male;
this.female = Sex.Female;
}
public void updateNetworth(double x)
{
this.netWorth = netWorth + x;
}
public String toString(){
return("\nName: " + this.firstname + this.lastname + "\n" +
"Address: " + this.homeaddress + "\nNet Worth: " + this.netWorth);
}
public static void main(String[] args)
{
Address a1 = new Address (258, "Masachu","New York","USA");
Person p1 = new Person("John","Brown",1998,Sex.Male,1000.00,a1);
System.out.println(p1.toString());
p1.updateNetworth(1000.00);
System.out.println(p1.toString());
}
}
public class Address {
private int streetNumber;
private String streetName;
private String city;
private String country;
public Address (int streetNumber, String streetName, String city, String country)
{
this.streetNumber = streetNumber;
this.streetName = streetName;
this.city = city;
this.country = country;
}
}
Whenever I run this my Address field is being printed out as Address#3feba861. I am unclear as to why this is so. So my Person constructor takes in the Address object, but it seems that I cannot print out the person object with the address in this way. How do I go about fixing this.
#Override
public String toString() {
return "Address{" +
"streetNumber=" + streetNumber +
", streetName='" + streetName + '\'' +
", city='" + city + '\'' +
", country='" + country + '\'' +
'}';
}

While Iterating through ArrayList using for loop instead of Iterator, why does the output reference an address instead of actual object?

I've created a list from objects from my user defined class called students.
class Student {
String name, phone, group;
Student(String name, String phone, String group) {
this.name = name;
this.phone = phone;
this.group = group;
}
}
And accessed it in the following way:
public static void main(String[] args) {
Student s1 = new Student("Ayush", "9841293412", "L1N1");
Student s2 = new Student("Rahul", "9842432423", "L1M1");
Student s3 = new Student("Gaurav", "984129231", "L1N2");
ArrayList<Student> al = new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
al.add(s4);
al.add(s5);
for(Student name:al){
System.out.println("Name: " + name);
}
But the output is referencing object like following:
Name: Student#1baf61
Name: Student#b5272
I don't know why this has happened.
Just extract the name field instead:
class Student {
String name, phone, group;
Student(String name, String phone, String group) {
this.name = name;
this.phone = phone;
this.group = group;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", phone='" + phone + '\'' +
", group='" + group + '\'' +
'}';
}
public static void main(String[] args) {
Student s1 = new Student("Ayush", "9841293412", "L1N1");
Student s2 = new Student("Rahul", "9842432423", "L1M1");
Student s3 = new Student("Gaurav", "984129231", "L1N2");
ArrayList<Student> al = new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
for (Student name : al) {
System.out.println("Name: " + name.name);
System.out.println("Name: " + name.getName()); // Using a getter
System.out.println(name); // Using toString
}
}
}
As a best practice use a getter or a toString implementation to better represent your model
You can override the toString method in your StudentClass or if u want only the name you can implement a getter method in your StundentClass..
class Student {
String name, phone, group;
Student(String name, String phone, String group) {
this.name = name;
this.phone = phone;
this.group = group;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", phone='" + phone + '\'' +
", group='" + group + '\'' +
'}';
}
usage toString
for(Student name:al){
System.out.println("Name: " + name);
}
output:
Name: Student{name='Ayush', phone='9841293412', group='L1N1'}
Name: Student{name='Rahul', phone='9842432423', group='L1M1'}
Name: Student{name='Gaurav', phone='984129231', group='L1N2'}
usage of your getter
for(Student name:al){
System.out.println("Name: " + name.getName());
}
output:
Name: Ayush
Name: Rahul
Name: Gaurav

how to sort an array of string records using comparator in java?

i have a string array data comprising of individual records. i.e., firstname,lastname,age,emailid,sex,address.
example:
static String[] users = {"Lola,Grimsdyke,89,lgrimsdyke0#facebook.com,Female,Newport Beach,CA","Sybilla,Martinetto,84,smartinetto1#google.it,Female,Anniston,AL","Casi,Roizn,78,croizn2#scribd.com,Female,San Jose,CA"};
how to extract each user record and sort them according to age using comparable interface?
First Thing you have to convert your string array to list.
String[] users = { "Lola,Grimsdyke,89,lgrimsdyke0#facebook.com,Female,Newport Beach,CA",
"Sybilla,Martinetto,84,smartinetto1#google.it,Female,Anniston,AL",
"Casi,Roizn,78,croizn2#scribd.com,Female,San Jose,CA" };
ArrayList<UserDetails> list=new ArrayList<>();
for (int i = 0; i < users.length; i++) {
String[] sp = users[i].split(",");
list.add(new UserDetails(sp[0], sp[1], Integer.parseInt(sp[2]), sp[3], sp[4], sp[05]));
}
for(UserDetails detail:list) {
System.out.println(detail);
}
class UserDetails {
String firstName;
String lastName;
int age;
String emailId;
String sex;
String address;
public UserDetails(String firstName, String lastName, int age, String emailId, String sex, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.emailId = emailId;
this.sex = sex;
this.address = address;
}
#Override
public String toString() {
return "UserDetails [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", emailId="
+ emailId + ", sex=" + sex + ", address=" + address + "]";
}
}
After that create agecomparator to compare age.
class AgeComparator implements Comparator<UserDetails> {
#Override
public int compare(UserDetails o1, UserDetails o2) {
return o1.age - o2.age;
}
}
After that sort using comparator.
System.out.println("After Sort");
AgeComparator ageComparator=new AgeComparator();
Collections.sort(list, ageComparator);
for(UserDetails detail:list) {
System.out.println(detail);
}

Create method to count occurrences of type char within an array

I need to create a method that searches a String array whether a specfic character exists in the array and returns an integer of the number of occurrences the character appears, I have looked on other posts to try and work it out myself but they are all arrays of int not String
I have another class name hence the array name being type Name.
public class Reg {
//Fields
private ArrayList<Name> Name;
//Constructors
public Reg() {
Name = new ArrayList<>();
}
//Methods
public int CountCharacterOccurrences (Char character){
}
}
Name Class:
public class Name implements Comparable<Name> {
//Fields
private String firstName;
private String familyName;
//Constructors
public Name() {
firstName = "";
familyName = "";
}
public Name(String firstName, String familyName) {
this.firstName = firstName;
this.familyName = familyName;
}
//Methods
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getFirstName() {
return firstName;
}
public String getFamilyName() {
return familyName;
}
public String getFullName() {
if (firstName.equals("") && familyName.equals("")) {
return "";
} else {
return firstName + " " + familyName;
}
}
#Override
public String toString() {
return "Name:[firstName=" + firstName + ", familyName=" + familyName + "]";
}
}
How do I add a method CountCharacterOccurences that accepts a char argument and returns an int signalling the number of occurrences.
Maybe this is what you mean:
class Reg{
private ArrayList<Name> names;
public Reg() {
names = new ArrayList<>();
}
public int countFirstNameOccurrences(char c) {
return names.stream() // get Stream<Name>
.map(Name::getFirstName) // convert Stream<Name> to Stream<String> using Name's firstName
.mapToInt(s -> s.length() - s.replace(String.valueOf(c), "").length()) // calculate every occurrence c in each firstName and get an IntStream
.sum(); // sum all the values
}
public static void main(String[] args) {
Reg reg = new Reg();
reg.names.add(new Name("John", "Doe"));
reg.names.add(new Name("Johnny ", "Doe"));
reg.names.add(new Name("Richard", "Roe"));
reg.names.add(new Name("James", "Roe"));
reg.names.add(new Name("Jane", "Roe"));
System.out.println(reg.countFirstNameOccurrences('J'));
}
}
Output:
4
as there are 4 J's in the first names in the list (John, Johnny, James and Jane)

two person object

import cs1.Keyboard;
import java.util.Scanner;
class Person
{
private String name;
private String persnr;
private String adress;
private int age;
public Person(String _name, String _persnr, String _adress, int _age)
{
name = name;
persnr = persnr;
adress = adress;
age = age;
}
public void byterNamn(String _name)
{
name = _name;
}
public void byterAdress(String _adress)
{
adress = _adress;
}
public void fyllerAr()
{
age = age + 1;
}
public String hamtaNamn()
{
return name;
}
public String hamtaPersonnmmer()
{
return persnr;
}
public String hamtaAdress()
{
return adress;
}
public int hamtaAlder()
{
return age;
}
public String toString()
{
String _toString;
_toString = "Namn: " + name + "\nÅlder: " + age;
_toString = _toString + "\nPersonnummer: " + persnr + "\nAdress: " + adress;
return _toString;
}
public p1()
{
System.out.print("namn: ");
name = Keyboard.readString();
System.out.print( "adress: " );
String adress = Keyboard.readString();
System.out.print( "ålder: " );
Integer age = new Integer();
age.parseInt(Keyboard.readint());
System.out.print( "personnummer: " );
String persnr = Keyboard.readString();
}
public p2()
{
System.out.print("namn: ");
name = Keyboard.readString();
System.out.print( "adress: " );
String adress = Keyboard.readString();
System.out.print( "ålder: " );
Integer age = new Integer();
age.parseInt(Keyboard.readint());
System.out.print( "personnummer: " );
String persnr = Keyboard.readString();
}
public static void main(String[] args)
{
String name = Keyboard.readString();
String persnr = Keyboard.readString();
String adress = Keyboard.readString();
int age = Keyboard.readint();
Person p1 = new Person(name, age, adress, personnummer);
String name = Keyboard.readString();
String persnr = Keyboard.readString();
String adress = Keyboard.readString();
int age = Keyboard.readint();
Person p2 = new Person(name, age, adress, personnummer);
}
}
hello.
I try to do so it is 2 people. where you should enter the age, name, address of both people and then print it after you enter what you want when the program runs. and i wondering how do i do return on public p1() and public p2() so i can do it. Or is it a easier way to do it?
This code does not compile. public p1() and public p2() are not valid method declarations. You must at least add a method return type after the public and before the method name, for example:
public Person p1()
Then I guess what you want to do is return a Person object from each of those two methods. Inside the method you must create a new Person object and then return it from the method:
return new Person(name, persnr, adress, age);
See Defining Methods and Returning a Value from a Method in Oracle's Java Tutorials.

Categories

Resources