I am working on my pet ownership system and struggle at a problem. To add a resident object, I need 5 fields which are phone, postcode, name, birthday and pet. Among them, phone, postcode, and name are compulsory fields, and the others are optional. An object can only be built with the existence of compulsory fields.
How can I do that, to differentiate between compulsory and optional fields? I just taught myself the OOP system. Really need a hint. Any answer is welcome!
The best way to do this is to make sure through prompt(user input) or string check(file input) if the input has the correct fields needed to correctly create your object(class)
After this use a programmer defined constructor
Documentation for that in the link
https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
to instantiate the object using the needed fields and I would use Set functions for optional inputs.
If the inputs do not match the needed inputs output a fail message and do not instantiate the object.
I hope this helps with your problem.
This is just an example of how you could approach the problem
public class Example{
String phone;
String postcode;
String name;
String birthday;
String pet;
public Example()
{
birthday="N/A";
pet="N/A";
}
public static void main(String[] args)
{
//Ask phone number
while(phone==null||phone=="")
{
//keep on asking
}
//Ask postcode
while(postcode==null||postcode=="")
{
//keep on asking
}
//Ask name
while(name==null||name="")
{
//keep on asking
}
//Ask birthday, and no need for checks
//Ask pet, and no need for checks
}
}
Related
I think it's stupid but I must know what that thing is (in the red circle), is it a variable or something? This is tutorial from YouTube (https://www.youtube.com/watch?v=lF5m4o_CuNg).
I want to learn some about this but when I don't even know name of that I can't search info about this.
That are variables of specific types which are available in android. They store information about objects which are defined in some xml files. Usually their purpose is to add some logic to some graphic objects like text field or button.
TL;DR: Those are called attributes
Java is an object-oriented programming language. It means that we can create classes, with attributes (variables) and methods (functions), to represent (abstract may be a better word) concepts of the real world.
Let's say we want to represent a person in our program. We need to store the person's name and their e-mail address.
We can create a class Person with 2 attributes: name and email.
public class Person {
String name;
String email;
}
Now we can create an instance of a Person, and fill the attributes with values:
public class Person {
String name;
String email;
public static void main(String[] args) {
Person person1 = new Person();
person1.name = "Alice";
person1.email = "alice#gmail.com";
}
}
Let's say that we want to find out the e-mail provider of a Person. We can do that by creating a method.
public class Person {
String name;
String email;
public String getEmailProvider() {
String emailProvider = email.split("#")[1];
return emailProvider;
}
public static void main(String[] args) {
Person person1 = new Person();
person1.name = "Alice";
person1.email = "alice#gmail.com";
String person1EmailProvider = person1.getEmailProvider();
System.out.println(person1EmailProvider);
// This prints: gmail.com
}
}
The cool part about object-orienting is that you can create multiple instances of a Person, and fill their attributes with different values. So if you need to represent a, say, Bob, you can just Person person2 = new Person() and then set the attributes to the values that you want.
This is a very basic explanation of object-oriented programming. The internet has plenty of information about it, and I deeply recommend you to study this if you're a beginner.
Those are 3 variables.
"private" is the access modifier,
"EditText" is a variable type
"Password" is name of the variable
I recently started learning java this year in my school. We've gotten to a short chapter where we are creating a class that calls multiple methods from inside the class or outside the class. Our teacher gave us a demo showing us an class using methods from another class. This is the code from his example of this and called the class Dog. He then creates another class called DogDriver. We then received a coding project. Here's what is must include. It's a program for a bank that must allow the owner to enter the bank account owner's name, money balance, and the amount the depositor would like withdrawn from their account. It will also need to allow the depositor to deposit and withdraw funds, and give error when the withdrawal exceeds the accounts balance. It needs 2 or more methods to call the program
I referenced back to the example he gave me and am having a hard time understanding the example so I can make the program. I think I get what it does, but when ever I try and code it myself, I seem to always get the “invalid method declaration; return type required”. I know I am doing something wrong but I would like to understand the way the program code I linked above works and how it can be used.
Any help is appreciated, Thank You
Here's my code. I was trying to understand the example program he created so I had taken it and edited it.
//January 27, 2015
public class Testing1{
private double Balance;
private String Name, Middle, Last;
public AccountBalance(){
Name = "Phillip";
Middle = "J.";
Last = "Fry";
Blance = 300;
}
public accountBalance(String FirstName, String MiddleName, String LastName, double InitialBal){
Name = FirstName;
Middle = MiddleName;
Last = LastName;
Balance = InitialBal;
}
public String Name(){
return Name;
}
public void SetBalance(double InitialBal){
Balance = InitialBal;
}
public double GetBalance(){
return Balance;
}
}
public AccountBalance(){...}
//and
public accountBalance(String FirstName, String MiddleName, String LastName, double InitialBal){...}
are (I assume you want them to be) constructors, therefore, they need to be the same name as the class name (here it is Testing1), and they are CASE SENSITIVE meaning AccountBalance does not equal accountbalance, eith change your constructors to match the class name :
public Testing(){...}
or refractor your class name to be AccountBalance
The error is because java thinks they are methods, which need return types.
Oh and, Balance = 300 is spelt wrong in your first constructor
First of all, if you would like to call a method from a different class, it must be public class. Then you can call those methods from your main method.
Dog myDog = new Dog();
myDog.colour("White");
Java Method Calling
For example, say I have the 3 classes Person, Student and Teacher. The Person class would have general details about the people (name, age, email etc) which both the Student and Teacher class will extend. On top of this though, these classes will also have their own unique fields (e.g. wage & courseTaught (or "tought"?) for Teacher and schoolYear & classNumber for Student). If I just show the initial code I've got, maybe someone could point me in the right direction. Because Person doesn't have a courseTaught field, currently I'm just getting the output "Josh (null)" rather than "Josh (Computer Science)". Any help would be appreciated :)
public class Main {
public static void main(String args[]){
Teacher t = new Teacher("Josh", "Computer Science");
System.out.println(t.name + " (" + t.courseTaught + ")");
}
}
public class Person {
String name;
public Person(String pName){
name = pName;
}
}
public class Teacher extends Person{
String courseTaught;
public Teacher(String tName, String tCourseTaught){
super(tName);
}
}
The problem is simpler than you think. You're on the right track but you forgot to assign courseTaught in your Teacher constructor. The initial value of courseTaught is null and it stays that way because you never assign it to anything.
You'd want something like this:
public Teacher(String tName, String tCourseTaught){
super(tName); // <- takes care of Persons's field
courseTaught = tCourseTaught; // <- but don't forget to set the new field, too.
}
And yes, "taught" is the correct word.
As an aside, since you did tag your question "oop", you may want to check out this article on encapsulation for some information about the use of "getters" and "setters".
so I'm a newbie learning 'bout classes and object orienting in java. Each instance of a mobile saves the model, owner name and number. So in the main file I try to make a method with those parameters and an identifier to create a new instance. However, compiling says that mobName already is defined within createMobile. It's supposed to make an instance which can be pointed to using "mob1". Any help?
class PhoneSystem{
public static void main(String[] args){
createMobile("mob1", "Android S4", "John Doe", 13374042);
}
public static void createMobile(String mobName, String brand, String owner, int number){
Mobile mobName = new Mobile();
mobName.SetBrand(brand);
mobName.SetOwner(owner);
mobName.SetNumber(number);
}
}
public static void createMobile(String mobName, String brand, String owner, int number){
Mobile mobName = new Mobile();
...
These two lines are where your problem resides. You have defined a String mobName. Afterwards, you attempt to define a variable with the same name as Mobile mobName. Variables cannot share the same name, even within method declaration and method. There's a unique case where this is possible, but that involves fields and instances and is beyond the scope of this question.
Since you want mob1 you should do:
Mobile mob1 = new Mobile();
Additionally, you have not specified if you want mob1 to be its name or its variable name. If you want the device to be known as mob1 you should probably make it so Mobile takes a device name as String. There's another way to associate the Mobile instance with a name via Map but since you're saying you're learning OO, that may also be outside of scope as it involves Collection.
However, the current code you've provided would result in mob1 going out of scope at the end of the method. Perhaps you wanted to return it to the main class?
public static Mobile createMobile(String mobName, String brand, String owner, int number){
Mobile mob1 = new Mobile();
...
return mob1;
}
This would allow you to create mob1 and pass it to your main method.
public static void createMobile(String mobileName, String brand, String owner, int number){
Mobile mobName = new Mobile();
mobName.SetBrand(brand);
mobName.SetOwner(owner);
mobName.SetNumber(number);
}
Here createMobile method first arg name and mobile object name are same that why u got error
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];
}
}