What changes should i perform in my code so that it could print the whole family
Have tried toString, i am only getting null. This is just a pretty simple code soo plss help.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* Created by Alpit on 26-05-2017.
*/
public class Fam {
String father;
String mother;
String sister;
String brother;
String r;
public Fam(String father, String sister, String brother, String mother) {
this.father = father;
this.sister = sister;
this.brother = brother;
this.mother = mother;
}
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
}
class add {
public static void main(String args[]) throws IOException {
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Object> arrayList = new ArrayList<>();
for (int i = 0; i < 2; i++) {
String f = obj.readLine();
String s = obj.readLine();
String b = obj.readLine();
String m = obj.readLine();
Fam fam = new Fam(f, s, b, m);
arrayList.add(fam);
}
for (Object x : arrayList) {
System.out.println(String.valueOf(x));
}
}
}
I am only getting the address of Object, This question can be considered to be a duplicate of this question but i was not able to understand by the solution provided there.
This is what i tried again
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* Created by Alpit on 26-05-2017.
*/
public class Fam {
String father;
String mother;
String sister;
String brother;
String r;
public Fam(String father, String sister, String brother, String mother) {
this.father = father;
this.sister = sister;
this.brother = brother;
this.mother = mother;
}
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
public String toString()
{
return r;
}
}
class add {
public static void main(String args[]) throws IOException {
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Object> arrayList = new ArrayList<>();
for (int i = 0; i < 2; i++) {
String f = obj.readLine();
String s = obj.readLine();
String b = obj.readLine();
String m = obj.readLine();
Fam fam = new Fam(f, s, b, m);
arrayList.add(fam);
}
for (Object x : arrayList) {
System.out.println(x.toString());
}
}
}
And this returns null.
You can override toString() from Object in your Class Fam.
What String.valueOf(object) does is that it calls the toString() method of class Object (in your case it is Fam).
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
So you would need to override the toString() method in Fam class like this:
public class Fam {
String father;
String mother;
String sister;
String brother;
String r;
public Fam(String father, String sister, String brother, String mother) {
this.father = father;
this.sister = sister;
this.brother = brother;
this.mother = mother;
}
.
.
.
#Override
public String toString() {
return this.father +" "+this.mother +" "+ this.sister +" "+ this.brother;
}
Additionally, you will need to make this change in your main method.
ArrayList<Fam> arrayList = new ArrayList<Fam>();
This way you will get your object printed. (PS: you can change the return format in toString() method.)
Implement your own toString() method. Do something like this:
class Fam {
String father;
String mother;
String sister;
String brother;
String r;
public Fam(String father, String sister, String brother, String mother) {
this.father = father;
this.sister = sister;
this.brother = brother;
this.mother = mother;
}
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(this.father);
builder.append(" ");
builder.append(this.sister);
builder.append(" ");
builder.append(this.brother);
builder.append(" ");
builder.append(this.mother);
return builder.toString();
}
}
class add {
public static void main(String args[]) throws IOException {
Fam family = new Fam("father", "sister", "brother", "mother");
System.out.println(family.toString());
}
}
I have implmented toString() here. I have used a StringBuilder to demonstrate how you can create your own method, inserting a space between "father, sister, brother, mother".
Running you get:
father sister brother mother
Your ArrayList is given a type parameter of Object. This is fine and all, but when you're trying to print the data in the for loop, you'll need to cast x to Fam. It would be easier to declare it like ArrayList<Fam> arrayList = new ArrayList<>(). Also, you can't simply print objects the way you're trying to do it. Object references hold the value of the memory address. You'll need to manually print the data by using the getter methods in your Fam class. You could also override the toString() method to do this if you want.
Related
import java.util.Arrays;
import java.util.Scanner;
public class employee{
public String name;
public class employee_address{
String street_name;
String city;
String zipcode;
String state;
String country;
}
public static void main(String []args){
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt();
employee[] employees_list = new employee[no_of_employees];
for(int i = 0;i < no_of_employees;i++){
employees_list[i].name = user_input.nextLine();
employees_list[I].employee_address = // this is it ?
}
}
}
In the code above I do understand that the employee_address is a class and can't be accessed
directly without an instance being created like in the code, that makes no sense. but how can I create an instance of the employee_address class that is associate with each employee.
like in the code above 'employee_address' is associated with every employee but how can the class 'employee_address' be initialised and how can I set the street_name, city and the rest of the members in the address class. any ideas would be appreciated.
You can't directly create an instance of inner class, the reason because since it is the property of another instance we always need to use it though the instance of parent variable.
Let's say you have a class, which have two propeties:
public class Employee {
public String name;
public EmployeeAddress emAddress;
}
to access emAddress you need to use through the instance of Employee class, for example -
Employee object = new Employee();
EmployeeAddress empAdd = object.new EmployeeAddress();
Full code:
public class Employee {
public String name;
public EmployeeAddress emAddress;
public class EmployeeAddress {
String street_name;
String city;
String zipcode;
String state;
String country;
public String getStreet_name() {
return street_name;
}
public void setStreet_name(String street_name) {
this.street_name = street_name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString() {
return "EmployeeAddress [street_name=" + street_name + ", city=" + city + ", zipcode=" + zipcode
+ ", state=" + state + ", country=" + country + "]";
}
}
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt(); // let's say no_of_employees = 1
Employee[] employees = new Employee[no_of_employees];
for (int i = 0; i < no_of_employees; i++) {
Employee object = new Employee();
object.setName("Virat Kohli");
EmployeeAddress empAdd = object.new EmployeeAddress();
empAdd.setCity("New Delhi");
empAdd.setCountry("India");
empAdd.setState("Delhi");
empAdd.setStreet_name("Chandni Chalk");
empAdd.setZipcode("741124");
object.setEmAddress(emAddress);
employees[i] = object;
}
System.out.println(employees[0]);
user_input.close();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EmployeeAddress getEmAddress() {
return emAddress;
}
#Override
public String toString() {
return "Employee [name=" + name + ", emAddress=" + emAddress + "]";
}
public void setEmAddress(EmployeeAddress emAddress) {
this.emAddress = emAddress;
}
}
I have modified your code to sonar standard.
Below code uses Java naming conventions (which your code does not).
Notes after the code.
import java.util.Scanner;
public class Employee {
private String name;
private EmployeeAddress address;
public class EmployeeAddress {
String streetName;
String city;
String zipcode;
String state;
String country;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int noOfEmployees = userInput.nextInt();
Employee[] employeesList = new Employee[noOfEmployees];
for (int i = 0; i < noOfEmployees; i++) {
employeesList[i] = new Employee();
employeesList[i].name = userInput.nextLine();
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
employeesList[i].address = employeeAddress;
employeesList[i].address.streetName = userInput.nextLine();
}
}
}
An inner class is a normal class. It is not a member of its enclosing class. If you want class Employee to have an [employee] address, as well as a [employee] name, you need to add another member variable to class Employee whose type is EmployeeAdress.
Employee[] employeesList = new Employee[noOfEmployees];
The above line creates an array but every element in the array is null. Hence you need to first create a Employee object and assign it to an element of the array. Hence the following line in my code, above:
employeesList[i] = new Employee();
Since EmployeeAddress is not a static class, in order to create a new instance, you first need an instance of the enclosing class, i.e. Employee. Hence the following line in the above code.
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
Since all your code is in class Employee, in method main you can directly access the members of both class Employee and EmployeeAddress. Nonetheless you need to be aware of the different access modifiers in java.
A few hints:
stick to naming conventions: class names in Java start with capital letters
use (class) definitions before using them (collect them at the top if not inconventient)
if you are sure you want to use inner classes, set them static, unless you want them to be entangled in generics.
Usually normal classes in each their own file are a lot more flexible and far easier to use
if you use objects that only carry public data, try to use final keyword and initialize them ASAP
use proper objects first, and after finishing them assign them to arrays. avan better would be the use of ArrayList and the like
if Employee contains EmployeeAddress, it should initialize it if conventient. so an object is always responsible for its own stuff
Use try/resrouce/catch
scanner.nextInt() can be problematic with newline/line breaks. For user input better readLine() and parse input
Code:
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
static public class EmployeeAddress {
public final String street_name;
public final String city;
public final String zipcode;
public final String state;
public final String country;
public EmployeeAddress(final Scanner pScanner, final PrintStream pOutPS) {
street_name = readLine(pScanner, pOutPS, "Please enter Street Name:");
city = readLine(pScanner, pOutPS, "Please enter City Name:");
zipcode = readLine(pScanner, pOutPS, "Please enter Zip Code:");
state = readLine(pScanner, pOutPS, "Please enter State:");
country = readLine(pScanner, pOutPS, "Please enter Country:");
}
}
static public String readLine(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
pOutPS.print(pPrompt);
final String value = pScanner.nextLine();
pOutPS.println();
return value;
}
static public int readInt(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
return Integer.parseInt(readLine(pScanner, pOutPS, pPrompt));
}
public final String name;
public final EmployeeAddress address;
public Employee(final Scanner pScanner, final PrintStream pOutPS) {
name = readLine(pScanner, pOutPS, "Please enter Employee Name: ");
System.out.println("Name: " + name);
address = new EmployeeAddress(pScanner, pOutPS);
}
public static void main(final String[] args) {
try (final Scanner user_input = new Scanner(System.in);
final PrintStream output = System.out;) {
final int no_of_employees = readInt(user_input, output, "Please enter number of users: ");
final Employee[] employees_list = new Employee[no_of_employees]; // either this line
final ArrayList<Employee> employees = new ArrayList<>(); // or this line
for (int i = 0; i < no_of_employees; i++) {
output.println("Creating user #" + (i + 1) + "...");
final Employee newEmployeeWithAddress = new Employee(user_input, output);
employees_list[i] = newEmployeeWithAddress; // either this line
employees.add(newEmployeeWithAddress); // or this line
}
}
}
}
I have to modify setter method and constructor of the Customer class to throw an InvalidNameException if the length of first_name and last_name field of customer class id less than six and has numbers/special characters.
SAMPLE INPUT : Jack
O/P : javax.naming.InvalidNameException.Customer.setFirstName(Customer.java:67)
I tried this code but it is showing errors.
import java.util.*;
class Customer
{
String name;
public void setFirstName(String name)
{
this.name = name;
char a[] = name.toCharArray();
if(a.length <6){
throw new InvalidNameException();
}
else{
Pattern p = Pattern.compile("[a-z]",Pattern.CASE_INSENSITIVE);
MAtcher m = p.matcher(name);
boolean b = m.find();
if(!b){
throw new InvalidNameException();
}
}
}
}
public class Source
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
Customer cus = new Customer();
cus.setFirstName(name);
}
}
This code works fine.
import java.util.*;
import java.util.regex.*;
import javax.naming.*;
class Customer{
private String firstname;
private String lastname;
public Customer(){
}
public Customer(String firstname, String lastname) throws InvalidNameException{
Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
Matcher matcherf = pattern.matcher(firstname);
Matcher matcherl = pattern.matcher(lastname);
if((firstname.length() < 6) || (lastname.length() < 6) || matcherf.find() || matcherl.find()){
throw new InvalidNameException(" ");
}else{
this.firstname = firstname;
this.lastname = lastname;
}
}
public void setFirstName(String firstname) throws InvalidNameException{
Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
Matcher matcherf = pattern.matcher(firstname);
if((firstname.length() < 6) || matcherf.find()){
throw new InvalidNameException(" ");
}else{
this.firstname = firstname;
}
}
public void setLastName(String lastname) throws InvalidNameException{
Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
Matcher matcherl = pattern.matcher(lastname);
if((lastname.length() < 6) || matcherl.find()){
throw new InvalidNameException(" ");
}else{
this.lastname = lastname;
}
}
public String getFirstName(){
return firstname;
}
public String getLastName(){
return lastname;
}
#Override
public String toString(){
return ("Name = "+firstname+" "+lastname);
}
}
public class Source{
public static void main(String[] args) throws InvalidNameException{
Scanner sc = new Scanner(System.in);
String first = sc.next();
String last = sc.next();
Customer c = new Customer();
c.setFirstName(first);
c.setLastName(last);
}
}
Firstly your code having a compilation issue.
Once you are throwing an exception from method or caller of method thatit should also throws the same exception.
throws explanation
import javax.naming.InvalidNameException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Question2 {
public static void main(String[] args) throws InvalidNameException {
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
Customer cus = new Customer();
cus.setFirstName(name);
}
}
class Customer
{
String name;
public void setFirstName(String name) throws InvalidNameException {
this.name = name;
char a[] = name.toCharArray();
if(a.length <6){
throw new InvalidNameException();
}
else{
Pattern p = Pattern.compile("[a-z]",Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(name);
boolean b = m.find();
if(!b){
throw new InvalidNameException();
}
}
}
}
For achieving this you need to create a custom exception class. also, java is case sensitive so write code in a proper manner. below is an example of a custom exception. The custom exception will help you to create your own exception which should be inherited from the root Exception class.
import java.util.*;
import java.lang.*;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Rextester
{
public static void main(String[] args) throws InvalidNameException {
String name = "mukes";
Customer cus = new Customer();
cus.setFirstName(name);
}
}
class Customer {
String name;
public void setFirstName(String name) throws InvalidNameException {
this.name = name;
char a[] = name.toCharArray();
if (a.length < 6) {
throw new InvalidNameException("Invalid Name");
} else {
Pattern p = Pattern.compile("[a-z]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(name);
boolean b = m.find();
if (!b) {
throw new InvalidNameException("Invalid Name");
}
}
}
}
class InvalidNameException extends Exception {
private static final long serialVersionUID = 1L;
InvalidNameException(String s) {
super(s);
}
}
here is working example. I just removed the scanner here for showing quick output.
Hello I wanna create a program that sorts the following csv file I'm trying to sort the file by their district. So the following program reads the file and is able to sort it but it sorts it by their name and I wanna change it so it sorts by district any help is appreciated.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortDistrict
{
private static final String COLUMN_SEPARATOR = ",";
public static void main(String[] args) throws Exception
{
InputStream inputStream = new FileInputStream("data.csv");
List<List<String>> lines = readCsv(inputStream);
// Create a comparator that compares the elements from column 0,
// in ascending order
Comparator<List<String>> c0 = createAscendingComparator(0);
// Create a comparator that compares the elements from column 2,
// in descending order
Comparator<List<String>> c1 = createDesendingComparator(2);
// Create a comparator that compares primarily by using c0,
// and secondarily by using c1
Comparator<List<String>> comparator = createComparator(c0, c1);
Collections.sort(lines, comparator);
OutputStream outputStream = new FileOutputStream("output.csv");
String header = "Last Name, First Name, Email, Address, Age, District, Gender";
writeCsv(header, lines, outputStream);
}
private static List<List<String>> readCsv(
InputStream inputStream) throws IOException
{
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
List<List<String>> lines = new ArrayList<>();
String line = null;
// Skip header
line = reader.readLine();
while (true)
{
line = reader.readLine();
if (line == null)
{
break;
}
List<String> list = Arrays.asList(line.split(COLUMN_SEPARATOR));
lines.add(list);
}
return lines;
}
private static void writeCsv(
String header, List<List<String>> lines, OutputStream outputStream)
throws IOException
{
Writer writer = new OutputStreamWriter(outputStream);
writer.write(header+"\n");
for (List<String> list : lines)
{
for (int i = 0; i < list.size(); i++)
{
writer.write(list.get(i));
if (i < list.size() - 1)
{
writer.write(COLUMN_SEPARATOR);
}
}
writer.write("\n");
}
writer.close();
}
#SafeVarargs
private static <T> Comparator<T>
createComparator(Comparator<? super T>... districts)
{
return (t0, t1) ->
{
for (Comparator<? super T> district : districts)
{
int n = district.compare(t0, t1);
if (n != 0)
{
return n;
}
}
return 0;
};
}
private static <T extends Comparable<? super T>> Comparator<List<T>>
createAscendingComparator(int index)
{
return createListAtIndexComparator(Comparator.naturalOrder(), index);
}
private static <T extends Comparable<? super T>> Comparator<List<T>>
createDesendingComparator(int index)
{
return createListAtIndexComparator(Comparator.reverseOrder(), index);
}
private static <T> Comparator<List<T>>
createListAtIndexComparator(Comparator<? super T> delegate, int index)
{
return (list0, list1) ->
delegate.compare(list0.get(index), list1.get(index));
}
}
I also have a Person class if it'll be any use
public class Person implements Comparable<Person> {
private String name;
private String email;
private String address;
private String residency;
private String gender;
private int age;
private int district;
public Person(String name, String email, String address, String gender, String residency, int district, int age) {
this.name = name;
this.address = address;
this.age = age;
this.district = district;
this.residency = residency;
this.gender = gender;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public int getAge() {
return age;
}
public String getResidency() {
return residency;
}
public int getDistrict() {
return district;
}
public String getGender() {
return gender;
}
public String toString() {
return (name + "," + email + "," + address + "," + age + "," + residency + "," + district + "," + gender);
}
public int compareTo(Person another) {
if (district == another.getDistrict())
return 0;
else if (district < another.getDistrict())
return -1;
else
return 1;
} // end of compareTo
} // end of Person
The csv file is quite big but here is a few lines
First Name, Last Name, Email, Address, Age, Residency, District, Gender
Colleen,Joyner,commodo.auctor#elementumat.net,Ap #697-1279 Nullam Road,30,Resident,4,Female
Fay,Parker,augue.ut.lacus#egetvarius.edu,"P.O. Box 234, 6576 Et, Ave",24,Resident,4,Female
TaShya,Atkinson,sem.egestas#urna.com,"6319 At, St.",45,Resident,15,Female
Curran,Shannon,massa#arcu.com,"980 In, Rd.",57,Resident,8,Male
Yolanda,Snyder,ipsum.ac#Sednullaante.org,"P.O. Box 769, 8207 Egestas Avenue",54,Non-Resident,4,Female
Candice,Weaver,ligula#Aenean.ca,"Ap #599-9287 Tellus, Rd.",35,Resident,9,Female
Yoshio,Silva,fames#Cumsociisnatoque.co.uk,Ap #327-6404 Dui St.,19,Resident,4,Male
Thanks in advance
You need to sort a large CSV file by a specific field and output result to another CSV file. The code will be complex and lengthy if you try to do this in Java.
Yet, with SPL, the open-source Java package, you only need one line of code:
A
1
>file("output.csv").export#ct(file("data.csv").cursor#cqt().sortx(District))
SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as sort.splx and invoke it in Java as you call a stored procedure:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st=con.prepareCall("call sortx()");
st.execute();
…
Or execute the SPL string within a Java program as we execute a SQL statement:
…
st = con.prepareStatement("=>file(\"output.csv\").export#ct(file(\"data.csv\").cursor#cqt().sortx(District))");
st.execute();
…
I'm learning about constructors, but the videos that I've watched don't seem to help and everything I find on google seems to describe it in an advanced way.
I want to write a simple program which takes two inputs, a name (String) and an id (integer) and then just outputs it as "id" - "name". So for example:
01 - hello
This is the program that I'm trying to fix:
import java.util.Scanner;
public class ConstructorTest {
public static void main(String[] args) {
ConstructorTest();
toString(null);
}
//Constructor
public ConstructorTest(){
Scanner name = new Scanner(System.in);
Scanner id = new Scanner(System.in);
}
// Method
public String toString(String name, int id) {
System.out.print(id + " - " + name);
return null;
}
}
The errors that I get, are saying that my methods and constructors are undefined.
A constructor creates ("constructs") a new object. You can then call methods against that object.
Here's a simple object:
public class MyObject {
private int id;
private String name;
public MyObject(int id, String name) {
this.id = id;
this.name = name;
}
// Other methods here, for example:
public void print() {
System.out.println(id + " " + name);
}
}
You would call this constructor like this:
MyObject thing = new MyObject(1, "test");
And then you could call its method like this:
thing.print();
So for your example, what you'd do in your main method is first prompt the user for id and name, then create an object using a constructor, and then call a method on the constructor.
public class ConstructorTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// get the id and name from the scanner (I would suggest using prompts)
String name = in.nextLine();
int id = in.nextInt();
// create an object:
ConstructorTest myObject = new ConstructorTest(id, name);
// call the method:
String myString = myObject.toString();
// print the result:
System.out.println(myString);
}
// private variables, effectively the "properties" stored by the object:
private int id;
private String name;
// constructor:
public ConstructorTest(int id, String name) {
this.id = id;
this.name = name;
}
// method
#Override // because this is a method in java.lang.Object and we're overriding it
public String toString() {
return id + " - " + name;
}
}
Try this:
import java.util.Scanner;
public class ConstructorTest {
private int id;
private String name;
public static void main(String[] args) {
String name = args[0];
int id = Integer.valueOf(args[1]);
ConstructorTest ct = new ConstructorTest(name, id);
System.out.println(ct);
}
public ConstructorTest(String n, int i) {
this.id = i;
this.name = n;
}
// Method
public String toString() {
return String.format("%d - %s", id, name);
}
}
Never, ever put I/O in a constructor.
This is not supposed to be a client class. I'm just making a class for others to use. I'm using this for a Highschool. For example i have classes for the address, teacher, students, principal, roomnumber, etc..But its not compiling for some odd reason. I believe its because I'm not declaring a field but not sure.
import java.io.*;
public class HighSchool {
// Constructors
public HighSchool() { }
public HighSchool(String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects ) {
this.title = title;
this.teacher = teacher;
this.roomNumber = roomNumber;
this.period = period;
this.String[] students = students;
this.String address =a ddress;
this.String subjects = subjects;
}
public class Classcourse (String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects
private String period;) {
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getteacher() {
return teacher;
}
public void setteacher(String teacher) {
this.teacher = teacher;
}
public int getroomNumber() {
return roomNumber;
}
public void setroomNumber (int roomNumber) {
this.roomNumber = roomNumber;
}
public String getperiod() {
return getperiod();
}
public void setperiod (String period) {
this.period = period;
}
public String[] getstudents () {
return students[];
}
public void setstudents[] (String[] students
private String address;) {
this.students = students;
}
public String getaddress() {
return address;
}
public void setaddress (String address) {
this.address = address;
}
public String getsubjects() {
return subjects;
}
public void setsubjects (String subjects) {
this.subjects = subjects;
}
}
// modifier method
public void addstudents(String students) {
String[] newstudents = new String[students.length + 1];
for (int i = 0; i < students.length; i++) {
newstudents[i] = students[i];
}
newstudents[students.length] = student;
students = newstudents;
}
public boolean isInClass(String students) {
for (int i = 0; i < students.length; i++) {
if (students[i].equals(students)) {
return true;
}
}
return false;
}
// static creator method
public static HighSchool readFromInput() throws IOException {
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a HighSchool title: ");
HighSchool newHighSchool = new HighSchool(kb.readLine());
String students = null;
do {
System.out.print("Enter a student, or press Enter to finish: ");
students = kb.readLine();
if (students != null){
newHighSchool.addstudents(students);
}
} while (students != null);
return newHighSchool;
}
// Variables (Fields)
private String title;
private String[] students;
}
In addition, you wrote something that doesn't make sense from the point of view of Java Compiler:
private String period;) {
- probably remove ")".
The second thing:
Take a look on the declaration of class Classcourse.
It rather sounds wrong, although it can be an issue of this site's editor or something...
An "overall" hint - java has a very "intelligent" compiler in the most of the cases it can say what's wrong exactly with your code, so, assuming you're a newbie in Java, try to understand what compiler says to you.
Good luck!
Some things I noticed about the code:
public String getperiod() {
return getperiod();
}
This code will cause a endless loop when you call this function.
private String address;) {
this.students = students;
}
The compiler will give an error about the ";)". Change it to "()" to fix this.
Furthermore, you should really tell us more about the errors it's giving you. We can't help you if you don't give us the compiler errors.