How to reconstruct a name with a split String in Java? - java

First some info about my project,
I'm following a tutorial task where the main goal is to learn to work with error handling,
but I'm not at that part quite yet, I am working with establishing the main classes.
Thats what I need a little help and guidance with,(but errors are supposed to come up and be detected
so that I can learn to fix them later, but that's not the main question here, just information.)
Here's 3 of the classes which I've completed.
Student with two private fields: Name name and CourseCollection course.
Name with two fields String firstName and String surname.
CourseCollection with ArrayList courses.
(Info: Later, I will work with class UserDatabase to collect and load a collection of students,
+ class DatavaseFormatException which will represent errors, but I think it would be easier to finish those 3 classes above first? Correct me if
I'm wrong.)
QUESTION:I need a little help with class Name, I don't think my work is correct.
My main issue is with the method String encode, and constructor Name(String encodedIdentity)
where I want to return the names, split by a ;. Here's what I have
enter code here
public class Name
//instanciating the persons first and last name as Strings.
private String firstName;
private String surname;
/**
* Constructor for objects of class Name- setting the text values for a name
*/
public Name(String firstName, String surname)
{
firstName = this.firstName;
surname = this.surname;
}
/**
* Constructor for objects of class Name- reconstructing the fields
* from a coded name
*/
public Name(String encodedIdentity)
{
//Here, the name is supposed to be coded as a text value, with the first
//and last names split with a ;
this.encodedIdentity=encodedIdentity;
//I am getting my first error here
}
//getters for firstname and surname here
/**
* This method will return the name, with the first and last name split
* by a ;
*/
public String encode()
{
//Could I use a split String here? If so how?
return firstName + ";" + surname;
}
}
I can guarantee I will need further help with my work. Thanks in advance, I find
people on StackOverflow to be very helpful as I don't have anyone (other than my books)
to ask for help. (I know you guys are not free teachers. But if anyone would voulenteer to help me outside of this I would highly appreciate it.
(Sorry if that's not allowed to ask for!))
EDIT: Thanks to you guys, my class is now compiling. I am not sure how to test it yet, but this is what I have now. Does it look correct?
public class Name
{
/**
* Constructor for objects of class Name- setting the text values for a name
*/
public Name(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
}
/**
* Constructor for objects of class Name- reconstructing the fields
* from a coded name
*/
public Name(String encodedIdentity)
{
String names = firstName + surname;
String[] fullname = names.split( "\\;");
if(fullname.length != 2 )
{
System.out.println(fullname);
}
}
/**
* Getting the firstname of the person
* #return firstName
*/
public String getFirstName()
{
return firstName;
}
/**
* Getting the surname of the person
* #return surname
*/
public String getSurname()
{
return surname;
}
/**
* This method will return the name, with the first and last name split
* by a ;
*/
public String encode()
{
String encode = (firstName + ";" + surname);
return encode;
}
}

If you are given an "encoded id", split it to get the names:
public Name(String encodedIdentity){
String[] names = split( ";", encodedIdentity );
if( names.length != 2 ) throw new IllegalArgumentError("...");
firstName = names[0];
surname = names[1];
}
One does not store all the variants with which an object's attributes may be specified. Therefore, there shouldn't be a field encodedIdentity.

First correct your name constructor with two fields
replace this
public Name(String firstName, String surname)
{
firstName = this.firstName;
surname = this.surname;
}
with
public Name(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
}
Also, can you paste the error from console here. so that it will be easier to find the exact problem.

Related

Print ArrayList from another Class

Evening everyone,
I am writing a code to allow students to search for internships. I have a class for Semesters, a class for Students(where student input is taken and stored into an ArrayList and the actual iSearch class. My code is basically doing everything I need it to do, except I have hit a brain block in trying to figure out the best way to output my ArrayList from the Student class out at the end of my program in the iSearch Class.
I am fairly new to Java, so if I haven't explained this correctly please let me know. I am trying to get the ArrayList's of student information to output at the end of the while loop in the iSearch Class.....so
To make this easy. Is it possible to print an Arraylist from another class.
A better way to solve this is to create a Student object for each student. In your current class the ArrayLists you are creating are deleted after every method call, since it is not referenced anymore.
Here is how I would do it:
Student Class:
public class Student {
String firstName;
String lastName;
String interest;
public Student(String firstName, String lastName, String interest) {
this.firstName = firstName;
this.lastName = lastName;
this.interest = interest;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getInterest() {
return interest;
}
}
In your iSearch class you create an ArrayList of students, which lets you add your students:
ArrayList<Student> students = new ArrayList<Student>();
do {
String firstName = input.next();
String lastName = input.next();
String interest = input.next();
students.add(new Student(firstName, lastName, interest));
} while (YOUR_CONDITION);
Then you can display each student by iterating through the ArrayList and accessing the getter and setter methods:
students.foreach(student -> {
System.out.println(student.getFirstName());
System.out.println(student.getLastName());
System.out.println(student.getInterest());
});
Editing this a little will help you to solve your problem, but this is the basic solution.

Homework - Providing Output F and other things

My task is to "design a class called employee that includes three instance variables, first name (string), last name (string), and monthly salary (double). Provide a constructor that initializes the threee instance variables. Provide set and get methods for each instance variable. [...] to get full credit, your programs should have no compilation errors and give correct outputs; they should also be well commented and appropriately formated."
Now, for all intents and purposes, this site helped me finish the shell of that homework yesterday, where I created the class, got the main to stop being annoying, initialized a constructor with 3 variables, and had set and get methods for them.
However, I also feel like I need to have some kind of actual instance variables that should be set'ed, get'ed, adn printf'ed out or something. Right now, the Command Prompt just self terminates on the first button press, because there's nothing for the program to actually DO.
In that way, I'm messing with my program as it will be displayed below. I can't quite get it to work, and would appreciate some insight into at least what I am doing wrong with the code below:
import java.util.Scanner;
public class Employee
{
public String FirstName, LastName; // String instance variables
public double Salary; //double floating-point instance variable
// main method begins program execution
public static void main( String[] args )
{
// create Scanner to enable user input in Dos
Scanner input = new Scanner(System.in );
}
// should introduce and initialize the constructor Employee
public Employee( String fName, String lName, double empSalary )
{
FirstName = fName;
LastName = lName;
Salary = empSalary;
}
// set First Name
public void setFirstName( String Steven ) // set the First Name
{
FirstName = Steven;
}
public void setLastName( String Dorsey ) // set the Last Name
{
LastName = Dorsey;
}
public void setSalary( double empSalary ) // set the Employee Salary
{
Salary = empSalary;
}
public String displayMessage()
{
// This statement calls Employee and should
// get the First Name from Input
System.out.printf( "Please enter the First Name\n");
getFirstName( string fName );
{
return FirstName;
}
System.out.printf( "Please enter the Last Name\n");
getLastName( string lName ) ); // get the Last Name
{
return LastName;
}
System.out.printf( "Salary: $%.2f\n");
getSalary( double empSalary )
{
return Salary;
}
}
} // End class
Now, here are my errors. provided this time by Textpad:
* Employee.java:54: error: ')' expected
getFirstName( string fName );
^
* Employee.java:54: error: illegal start of expression
getFirstName( string fName );
^
* Employee.java:60: error: ')' expected
getLastName( string lName ) ); // get the Last Name
^
* Employee.java:60: error: illegal start of expression
getLastName( string lName ) ); // get the Last Name
^
* Employee.java:60: error: ';' expected
getLastName( string lName ) ); // get the Last Name
^
* Employee.java:66: error: '.class' expected
getSalary( double empSalary )
^
* Employee.java:66: error: ';' expected
getSalary( double empSalary )
You don't have semicolons after your function names.
So, the following:
getLastName( string lName ) ); // get the Last Name
{
return LastName;
}
should instead be
getLastName( string lName ) ) // get the Last Name
{
return LastName;
}
Hope it helps, I didn't read through the rest of the code.
Your code shows that you probably have some misconceptions about how Java and programming languages in general work:
e.g. in the snippet:
public void setFirstName( String Steven ) // set the First Name
{
FirstName = Steven;
}
the naming of the String parameter Steven is very peculiar. Most programmers would name the parameter firstName or pFirstname because it holds a String variable. In some cases the content of that variable might be "Steven". Please note how I wrote the parameter names in bold while the variable content is put in quotes. The concepts variable and parameter are important to grasp before you'r code will function right. You might want to check your code along these lines for all the other concepts that you were asked to do in your assignment. Learning is about understanding the difference between a misconception and the right concept. Please don't get frustrated that your question got negative points. People on stackoverflow are expecting the people who ask questions to do the basic analysis of the problem themselves and then ask for help when they get stuck at a point where all the analysis didn't help.
try this:
public class Employee {
public String FirstName, LastName; // String instance variables
public double Salary; //double floating-point instance variable
//should introduce and initialize the constructor Employee
public Employee( String fName, String lName, double empSalary ) {
FirstName = fName;
LastName = lName;
Salary = empSalary;
}
public void setFirstName( String Steven ) // set the First Name
{
FirstName = Steven;
}
public void setLastName( String Dorsey ) // set the Last Name
{
LastName = Dorsey;
}
public void setSalary( double empSalary ) // set the Employee Salary
{
Salary = empSalary;
}
public String getFirstName()
{
return FirstName;
}
public String getLastName()
{
return LastName;
}
public double getSalary(){
return Salary;
}
public void displayEmployee(){
System.out.println("FirstName : "+FirstName);
System.out.println("LastName : "+LastName);
System.out.println("Salary : "+Salary);
}
//main method begins program execution
public static void main( String[] args )
{
// create Scanner to enable user input in Dos
Scanner input = new Scanner(System.in );
System.out.println("Enter employee details :");
Employee emp=new Employee(input.next(), input.next(), input.nextDouble());
emp.displayEmployee();
}
}// End of class

Integer.toString(argument) or toString(argument)

I've written up some code for a Credit card class, pasted below. I have a constructor that takes in the said variables, and am working on some methods to format these variable's into strings such that the end output will be something along the lines of
Number: 1234 5678 9012 3456
Expiration date: 10/14
Account holder: Bob Jones
Is valid: true
(Won't format correctly - I'm unsure how to do it, would be greatful of someone can edit for me :) )
My question is, in the line
String shortYear = Integer.toString(expiryYear).substring(2,4);
Why won't the following work:
toString(argument).substring(2,4)
I would have imagined it wound have worked (expiryYear is essentially declared as an instance variable of type int). I've consulted my book (The official Java Tutorial also found online), and can't seem to find anything. I didn't even know about Integer.toString, a friend told me about that after trying to play with toString(), so it would be even more greatly appreciated if someone could also tell me where I can find these sorts of methods (I don't think they're in my book)
public class CreditCard {
private int expiryMonth;
private int expiryYear;
private String firstName;
private String lastName;
private String ccNumber;
public CreditCard(int expiryMonth, int expiryYear, String firstName, String lastName, String ccNumber) {
this.expiryMonth = expiryMonth;
this.expiryYear = expiryYear;
this.firstName = firstName;
this.lastName = lastName;
this.ccNumber = ccNumber;
}
public String formatExpiryDate() {
String shortYear = Integer.toString(expiryYear).substring(2, 4);
String expiryDate = expiryMonth + "/" + shortYear;
return expiryDate;
}
public static void main(String[] args) {
CreditCard cc1 = new CreditCard(10, 2014, "Bob", "Jones", "1234567890123456");
System.out.print(cc1.formatExpiryDate());
}
}
Try String.valueOf(expiryYear).substring(2,4)

Efficient way to split an array and organize into multiple array

I got a String[] which contains of multiple user details. Something like this:
Wilson#$20#$Male=#=Raymond#$25#$Male=#=Sophie#$20#$Female
I wanted to split the string up and organize it into multiple array. Such as one array for Name, one array for Age and another array for Gender. Up to this point I managed to split the String[] into something like this.
String[] User = student.split("=#=");
User[0] = Wilson#$20#$Male
User[1] = Raymond#$25#$Male
User[2] = Sophie#$20#$Female
I don't really know how to organize it from this point. Any comments and answers are highly appreciated!
EDIT
Wilson#$20#$Male=#=Raymond#$25#$Male=#=Sophie#$20#$Female
The above part is actually a value that is returned from the server and I wanted to handle this value. Thank you for all the replies. I think I understand a bit in theory wise, but I'm having slightly issue in implementing codes.
I agree with the suggestions of creating a class for each user - it's the Object Oriented way. So I included it in the example below. But you could probably change it easy enough if you want to do arrays or some other structure.
However, what I want to add is a way to use the Java classes java.util.regex.Pattern and java.util.regex.Matcher to extract both records AND fields in one go from your input string. (I haven't programmed for Android, I assume they are available though.)
The general plan for the pattern is: (record delimiter or nothing)(field1)(delim)(field2)(delim)(lastfield)(record delimiter + rest of input)
The algorithm basically loops through the input with the above pattern. The pattern extracts various groups for the fields (depending on how your record's format) and then also a last group that contains the remainder of the input string. This remainder is used as the new input string for the next loop. So each iteration of the loop does one record.
Here is more complete example code which you can run. You might need to study up on regular expressions to understand the pattern, which is the important part of the algorithm. You can start with the Javadoc for the java.util.regex.Pattern class.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestPatternMatch {
public static void main(String[] args) {
List<User> result = new ArrayList<>();
String input =
"Wilson#$20#$Male=#=Raymond#$25#$Male=#=Sophie#$30#$Female";
Pattern recPatt =
Pattern.compile("^(=#=|.{0})(.+?)#\\$(\\d+)#\\$(.+?)(?==#=)(.*$)");
// ^match start of line
// ^match record delimiter or nothing
// ^match name field (reluctant)
// ^match field delim
// ^match age field
// ^match field delim
// match gender field^
// zero-width (non recording) lookahead for record delimiter^
// match rest of line until end^
Matcher recMatcher;
String workStr = input; // start with whole input
while (workStr != null && workStr.length() > 0) {
recMatcher = recPatt.matcher(workStr);
if (recMatcher.matches() && recMatcher.groupCount() >= 5) {
result.add(
new User(
recMatcher.group(2), //name
Integer.parseInt(recMatcher.group(3)), //age
recMatcher.group(4) //gender
)
);
workStr = recMatcher.group(5); // use tail for next iteration
} else {
workStr = null;
}
}
System.out.println(result); //show result list contents
}
}
class User {
String name;
int age;
String gender;
/** All argument constructor */
public User(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
/** Show contents of object fields */
public String toString() {
return "User ["+ name + ", " + age + ", " + gender + "]";
}
}
The basic pattern structure can be reused for many different record formats.
Create a User object to store all fields (name, age, gender) and create a list to hold all data.
Your best bet here, is to use an object to hold these values. Objects are the standardized way to hold values that relate to one another, in one Object. ie:
public class Person
{
private String name;
private int age;
private String gender;
// Gender could be a boolean value really, but you've stored it as a String.
}
In the constructor you would request each value and assign it to these fields. It would look something like:
public Person(String name, int age, String gender)
{
this.name = name;
// etc etc
}
That way you have one array, with no need to do any tokenizing of Strings to get to individual values :). You will also need to implement some Accessors and Mutators to get at the values within the Object.
Why not create a User class and maintain a list of User instances.
class User {
String name;
String gender;
int age;
}
The best solution would be to create an class User. If you want to avoid it, try:
String[] User = student.split("=#=");
String [][] details=new String[user.length][3];
String [] temp=new String[3];
for(int i=0;i<User.length;i++){
temp=User.split("//");
for(j=0;j<3;j++){
details[i][j]=temp[j];
}
}

Creating objects from data entered by user

I'm working on a homework project that requires me to create an object from data entered by a user. I have a class called Person which takes the basic information, a class called Customer which extends the Person class and includes a customer number and a class called Employee which extends the Person class and returns a social security number.
I have pasted the code from my main program below. I'm a little confused on a couple of things. First when I'm collecting the information (first name, last name etc) amd I supposed to be accessing my Person class in there somehow?
Second I guess more plainly, how do I create the object? so far in all of the examples I have read online I find they seem to enter the information already like if I were to have it say
Person firstName = new Person(Jack);
Although I am collecting the information from the user so I don't see how to tell it like
Person firstName = new Person (enter info from user here);
Finally and again this is a really dumb question but I have to create a static method that accepts a Person object.
To create the static method I'm assuming it is
Public Static print()
but how do I tell it to print something from the person class? how does it know?
Most of my examples in the book include a class that contains all of the information instead of making the user enter it which is confusing because now I'm being told the user has the freedom to type what they want and I need to collect that information.
import java.util.Scanner;
public class PersonApp
{
public static void main(String[] args)
{
//welcome user to person tester
System.out.println("Welcome to the Person Tester Application");
System.out.println();
Scanner in = new Scanner(System.in);
//set choice to y
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
//prompt user to enter customer or employee
System.out.println("Create customer or employee (c/e): ");
String input = in.nextLine();
if (input.equalsIgnoreCase("c"))
{
String firstName = Validator.getString(in, "Enter first name: ");
String lastName = Validator.getString(in, "Enter last name: ");
String email = Validator.getEmail(in, "Enter email address: ");
String custNumber = Validator.getString(in, "Customer number: ");
}
else if(input.equalsIgnoreCase("e"))
{
String firstName = Validator.getString(in, "Enter first name: ");
String lastName = Validator.getString(in, "Enter last name: ");
String email = Validator.getEmail(in, "Enter email address: ");
int empSoc = Validator.getInt(in, "Social security number: ");
}
}
System.out.println("Continue? y/n: ");
choice = in.next();
}
}
First, I observe that there isn't a Person object. I assume you'll get around to creating that, so I'm not going to concern myself too much with it.
Insofar as actually getting the data, you're halfway there. Depending on how you want to frame the Person object, you can create a new Customer or Employee object by passing the values which you received from the user.
Customer customer = new Customer(firstName, lastName, email, custNumber);
or
Employee employee = new Employee(firstName, lastName, email, empSoc);
Here's the snippet of both:
public class Person {
public Person (String first, String last, String email) {
// You'd fill in code here for handling the variables
}
// ...
}
public class Customer extends Person {
public Customer (String first, String last, String email, String custNo) {
super(first, last, email);
// You'd fill in code here for handling the variables
}
// ...
}
public class Employee extends Person {
public Employee (int social) {
super(first, last, email);
// You'd fill in code here for handling the variables
}
// ...
}
To print something from the Person class, using that static method (why? You could override toString() instead), you frame it such that your Person object has accessors to each of the fields relevant to a Person. This would mean you have a getFirstName(), getLastName(), and so forth, relevant to the object if it's an employee or a customer. (I leave that as an exercise to you.)
In that sense, one would then only require calls to those accessors to print the value.
public static void print(Person p) {
System.out.println(p.getFirstName()) + " " + p.getLastName()); // You can get the trend from here.
}
To print the Person object you can just use the System.out.println() if you just want to print it to the command line, but you'll get some unreadable nonsense.
What the println() method does is, if the object is not a String call it's toString() method, because all objects have one, it is defined in java.lang.Object. But that method gives us unreadable things mentioned above, so you have to override it to do something like
public class Person
{
String firstName;
String Lastname;
public Person(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String toString()
{
// Create a String that represents this object
return "This person is called " + firstName + " " + lastName;
}
}
To create an object you can read the Strings from the commandline and then pass them into the constructor as Makoto suggests.

Categories

Resources