How can i improve this code?
I had an assignment that goes like this:
-----------------------------------------------------------------
Write a class named Person containing the following instance variables with suitable types:
name, personal number, address, age
The following methods must be included in the class:
the constructor Person that initiates all instance variables
changeName that changes the name using a parameter
changeAddress that changes the address using a parameter
incrementAge that adds one to the current age
getName that returns the name
getPerNo that returns the personal number
getAge that returns the age
getAddress that returns the address
toString that returns a nicely formatted string containing all the data contained in a Person object. The method is called by using the objects (or reference) name.
Write a test program that tests all of the methods in the class Person. The tests must follow each other in this order:
Create two Person objects; person1 and person2. The user must type in the starting values for all the data for each object.
Print out all data for both objects.
Allow the user to change the name and address of person1.
Increment the age of person2.
-----------------------------------------------------------------------------------------------------
I wrote some code that works, but i'm not sure if it's the right way. What can i improve in it?
-----------------------------------------------------------------------------------------------------
Code Java:
[CODE]
package javaLab_4;
import java.util.Scanner;
public class Person {
public String name;
public String adress;
public int age;
public long personalNumber;
//Objects constructor with parameters:
public Person(String personName, String personAdress, int personAge, long personPerNum){
Scanner userInput = new Scanner(System.in);
System.out.println("\n>Type the name: ");
personName = userInput.nextLine();
name = personName;
//name = userInput.nextLine();
System.out.println(">Type the adress: ");
personAdress = userInput.nextLine();
adress = personAdress;
//or adress = userInput.nextLine();
System.out.println(">Type in the age: ");
personAge = userInput.nextInt();
age = personAge;
//or age = userInput.nextInt();
System.out.println(">Type in the personal number: ");
personPerNum = userInput.nextLong();
personalNumber = personPerNum;
//or personalNumber = userInput.nextLong();
}//End of Person Constructor.
public void changeName(String newName){
Scanner userInput = new Scanner(System.in);
System.out.println("\n>Enter a new name: ");
newName = userInput.nextLine();
name = newName;
}//End of changeName method.
public void changeAdress(String newAdress){
Scanner userInput = new Scanner(System.in);
System.out.println("\n>Enter a new adress: ");
newAdress = userInput.nextLine();
adress = newAdress;
}//End of changeAdress method.
public void incrementAge(){
age++;
}//End of incrementAge method.
public String getName(){
return "Name: "+name;
}//End of getName method.
public String getPerNo(){
return "Personal number: "+personalNumber;
}//End of getperNo method.
public String getAge(){
return "Age: "+age;
}//End of getAge method.
public String getAdress(){
return "Adress: "+adress;
}//End of getAdress method.
public String toString(){
return "\n>Credentials:\n--------------------------" +
"\n-Name: "+name+"\n-Adress: "+
adress+"\n-Age: "+age+"\n-Personal number: "+personalNumber+"\n";
}
}
[/CODE]
Test:
Code Java:
[CODE]
package javaLab_4;
public class PersonTest {
public static void main(String[] args) {
Person person1 = new Person(null, null, 0, 0);
Person person2 = new Person(null, null, 0, 0);
System.out.println(person1.toString());
System.out.println(person2.toString());
person1.changeName(null);
person1.changeAdress(null);
person2.incrementAge();
//Person1:
System.out.println(person1.getName()+"\n"+person1.getPerNo()+"\n"+person1.getAdress()+"\n-----------------");
//Person2:
System.out.println(person2.getName()+"\n"+person2.getPerNo()+"\n"+person2.getAge());
}
}
[/CODE]
---------------------------------------------------------------------------------------------------------------------------------------
My thoughts are:
-In the test class, i had to use null pointers to fill out the parameters, can it be done differently.
-When using the queries, i had to put them in System.out.print statements to see them. Why can't i just invoke the method on it's own and still see it on the screen?
PS: i'm using Eclipse Helios to compile and run all my java classes. If i try in command (cmd) i get an error (Symbol not found).
Re: How can i improve this code?
Quote:
If i try in command (cmd) i get an error (Symbol not found).
Can you copy and post the full text of the error message.
To copy the contents of the command prompt window:
Click on Icon in upper left corner
Select Edit
Select 'Select All' - The selection will show
Click in upper left again
Select Edit and click 'Copy'
Paste here.
You should get all the data for the Person object outside of the Person constructor. That allows you to negotiate with the user about the data and allow the user to end the input process and not leave a Person object half built.
Re: How can i improve this code?
This is the error i get if i compile the PersonTest.java with both of the files seperate but in one folder (package javaLabs_4):
__________________________________________________ __________________________
C:\Users\ziplague\Desktop\javaLabs_4>javac PersonTest.java
PersonTest.java:5: error: cannot find symbol
Person person1 = new Person(null, null, 0, 0);
^
symbol: class Person
location: class PersonTest
PersonTest.java:5: error: cannot find symbol
Person person1 = new Person(null, null, 0, 0);
^
symbol: class Person
location: class PersonTest
PersonTest.java:6: error: cannot find symbol
Person person2 = new Person(null, null, 0, 0);
^
symbol: class Person
location: class PersonTest
PersonTest.java:6: error: cannot find symbol
Person person2 = new Person(null, null, 0, 0);
^
symbol: class Person
location: class PersonTest
4 errors
C:\Users\ziplague\Desktop\javaLabs_4>
__________________________________________________ _________________________________
This error comes up if i compile it all in one java file (meaning i insert the main method before the last parentheses in the Person Class.)
__________________________________________________ ________________________________
C:\Users\ziplague\Desktop>javac Person.java
Person.java:92: error: class, interface, or enum expected
}
^
1 error
C:\Users\ziplague\Desktop>javac Person.java
C:\Users\ziplague\Desktop>java Person
Exception in thread "main" java.lang.UnsupportedClassVersionError: Person : Unsu
pported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknow n Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: Person. Program will exit.
__________________________________________________ ________________________________
And this is the error that i get when i compile them separately (meaning i compile the PersonTest which has the main method and it makes the Person Class work):
__________________________________________________ __________________________________
C:\Users\ziplague\Desktop>javac PersonTest.java
C:\Users\ziplague\Desktop>java PersonTest
Exception in thread "main" java.lang.UnsupportedClassVersionError: PersonTest :
Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknow n Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: PersonTest. Program will exit.
__________________________________________________ ___________________________________
But in Eclipse everything runs smoothly, no errors, and prints out the results that i'm after. weird.
Re: How can i improve this code?
Quote:
Unsupported major.minor version 51.0
That message says the the class file was created by java version 1.7 and the java program is an older version (not 1.7)
Does your IDE use a different version of java than available to the command line?
Re: How can i improve this code?
Quote:
Originally Posted by
Norm
That message says the the class file was created by java version 1.7 and the java program is an older version (not 1.7)
Does your IDE use a different version of java than available to the command line?
oops. Yes, cmd uses version 1.6, but why? i have both installed and the paths and classpaths are correct.
Re: How can i improve this code?
Anyway, i will fix that. But my main concern is to try to improve the code, i feel as if i deviated from the assignment instructions. Especially concerning the instance variables and the creation of new objects.
Re: How can i improve this code?
Quote:
Originally Posted by
Norm
You should get all the data for the Person object outside of the Person constructor. That allows you to negotiate with the user about the data and allow the user to end the input process and not leave a Person object half built.
What do you mean by outside the person constructor, and what data do you mean?
What's the problem with having an Person object half built, what if a person doesn't have a personal number, in this case it will be empty. Is that what u mean or something else?
Can you link me to an example?
Re: How can i improve this code?
Quote:
what if a person doesn't have a personal number, in this case it will be empty. Is that what u mean or something else?
Something like that.
You are connecting the creation of the Person object to the presence of a console input. When you move to a GUI program then the constructor will have to be changed. Remove the I/O from the constructor. Get the data outside of the class and pass the data in the constructor call.
Re: How can i improve this code?
Quote:
Originally Posted by
Norm
Something like that.
You are connecting the creation of the Person object to the presence of a console input. When you move to a GUI program then the constructor will have to be changed. Remove the I/O from the constructor. Get the data outside of the class and pass the data in the constructor call.
I'm sorry, i don't seem to understand what data you're talking about specifically. There is a lot of different data inside the class and inside the constructor. You're saying to put it outside the class? How's that going to work? i need to have class variables that get their value from user input, and the constructor should associate the user input to the class variables. If i remove them (and i don't know what is "them") to outside the class, then they won't be part of the class or constructor. You're confusing me. Could you refer to specific lines of code please, or write a small example?
Re: How can i improve this code?
Quote:
i need to have class variables that get their value from user input
Remove all user I/O code from the constructor. Get the values and use them in the constructor to pass them to the class.
pseudo code:
Get <the data for the class> from the user
TheClass aClassObj = new TheClass(<the data for the class>); // create an object with that data
Re: How can i improve this code?
Quote:
Originally Posted by
Norm
Remove all user I/O code from the constructor. Get the values and use them in the constructor to pass them to the class.
you say Get the values, how? i need to have i/o somewhere to get the values. Where should i put the i/o?
here's what i did:
Code Java:
import java.util.Scanner;
public class Person {
String name;
String adress;
int age;
long personalNumber;
public Person(String personName, String personAdress, int personAge, long personPerNum){
//Scanner userInput = new Scanner(System.in);
//System.out.println("\n>Type the name: ");
//personName = userInput.nextLine();
name = personName;
//name = userInput.nextLine();
//System.out.println(">Type the adress: ");
//personAdress = userInput.nextLine();
adress = personAdress;
//or adress = userInput.nextLine();
//System.out.println(">Type in the age: ");
//personAge = userInput.nextInt();
age = personAge;
//or age = userInput.nextInt();
//System.out.println(">Type in the personal number: ");
//personPerNum = userInput.nextLong();
personalNumber = personPerNum;
//or personalNumber = userInput.nextLong();
}//End of Person Constructor.
public void changeName(String newName){
Scanner userInput = new Scanner(System.in);
System.out.println("\n>Enter a new name: ");
newName = userInput.nextLine();
name = newName;
}//End of changeName method.
public void changeAdress(String newAdress){
Scanner userInput = new Scanner(System.in);
System.out.println("\n>Enter a new adress: ");
newAdress = userInput.nextLine();
adress = newAdress;
}//End of changeAdress method.
public void incrementAge(){
age++;
}//End of incrementAge method.
public String getName(){
return "Name: "+name;
}//End of getName method.
public String getPerNo(){
return "Personal number: "+personalNumber;
}//End of getperNo method.
public String getAge(){
return "Age: "+age;
}//End of getAge method.
public String getAdress(){
return "Adress: "+adress;
}//End of getAdress method.
public String toString(){
String toString = "\n>Credentials:\n--------------------------" +
"\n-Name: "+name+"\n-Adress: "+
adress+"\n-Age: "+age+"\n-Personal number: "+personalNumber+"\n";
return toString;
}
}
//Person test class with the main method
package javaLab_4;
import java.util.Scanner;
public class PersonTest {
public static void main(String[] args) {
Person person1 = new Person(null, null, 0, 0);
Person person2 = new Person(null, null, 0, 0);
//change code starts here:
Scanner userInput = new Scanner(System.in);
System.out.println("\n>Type the name: ");
person1.name = userInput.nextLine();
System.out.println(">Type the adress: ");
person1.adress = userInput.nextLine();
System.out.println(">Type in the age: ");
person1.age = userInput.nextInt();
System.out.println(">Type in the personal number: ");
person1.personalNumber = userInput.nextLong();
System.out.println("\n>Type the name: ");
person2.name = userInput.nextLine();
System.out.println(">Type the adress: ");
person2.adress = userInput.nextLine();
System.out.println(">Type in the age: ");
person2.age = userInput.nextInt();
System.out.println(">Type in the personal number: ");
person2.personalNumber = userInput.nextLong();
//changed code ends here:
System.out.println(person1.toString());
System.out.println(person2.toString());
person1.changeName(null);
person1.changeAdress(null);
person2.incrementAge();
//Person1:
System.out.println(person1.getName()+"\n"+person1.getPerNo()+"\n"+person1.getAdress()+"\n-----------------");
//Person2:
System.out.println(person2.getName()+"\n"+person2.getPerNo()+"\n"+person2.getAge());
}
}
i moved the i/o to the main method, is that better or did you mean put it before the constructor in the Person class?
Re: How can i improve this code?
Quote:
Where should i put the i/o?
Move it to before where you call the constructor with the data that you read in.
When you change your app to use GUI, you won't have to change anything in the Person class. The data needed by the class will be obtained somewhere else.
Re: How can i improve this code?
When i do that i get an error :
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token(s), misplaced construct(s)
Syntax error on token ""\n>Type the name: "", delete this token
Syntax error on token "name", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
Syntax error on token "">Type the adress: "", delete this token
Syntax error on token "adress", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
Syntax error on token "">Type in the age: "", delete this token
Syntax error on token "age", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
Syntax error on token "">Type in the personal number: "", delete this token
Syntax error on token "personalNumber", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
Syntax error on token ""\n>Type the name: "", delete this token
Syntax error on token "name", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
Syntax error on token "">Type the adress: "", delete this token
Syntax error on token "adress", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
Syntax error on token "">Type in the age: "", delete this token
Syntax error on token "age", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
Syntax error on token "">Type in the personal number: "", delete this token
Syntax error on token "personalNumber", VariableDeclaratorId expected after this token
at javaLab_4.Person.<init>(Person.java:12)
at javaLab_4.PersonTest.main(PersonTest.java:7)
Code Java:
public class Person {
String name;
String adress;
int age;
long personalNumber;
Scanner userInput = new Scanner(System.in);
System.out.println("\n>Type the name: ");
person1.name = userInput.nextLine();
System.out.println(">Type the adress: ");
person1.adress = userInput.nextLine();
System.out.println(">Type in the age: ");
person1.age = userInput.nextInt();
System.out.println(">Type in the personal number: ");
person1.personalNumber = userInput.nextLong();
System.out.println("\n>Type the name: ");
person2.name = userInput.nextLine();
System.out.println(">Type the adress: ");
person2.adress = userInput.nextLine();
System.out.println(">Type in the age: ");
person2.age = userInput.nextInt();
System.out.println(">Type in the personal number: ");
person2.personalNumber = userInput.nextLong();
public Person(String personName, String personAdress, int personAge, long personPerNum){
//Scanner userInput = new Scanner(System.in);
//System.out.println("\n>Type the name: ");
//personName = userInput.nextLine();
name = personName;
//name = userInput.nextLine();
//System.out.println(">Type the adress: ");
//personAdress = userInput.nextLine();
adress = personAdress;
//or adress = userInput.nextLine();
//System.out.println(">Type in the age: ");
//personAge = userInput.nextInt();
age = personAge;
//or age = userInput.nextInt();
//System.out.println(">Type in the personal number: ");
//personPerNum = userInput.nextLong();
personalNumber = personPerNum;
//or personalNumber = userInput.nextLong();
}//End of Person Constructor.
public void changeName(String newName){
Scanner userInput = new Scanner(System.in);
System.out.println("\n>Enter a new name: ");
newName = userInput.nextLine();
name = newName;
}//End of changeName method.
public void changeAdress(String newAdress){
Scanner userInput = new Scanner(System.in);
System.out.println("\n>Enter a new adress: ");
newAdress = userInput.nextLine();
adress = newAdress;
}//End of changeAdress method.
public void incrementAge(){
age++;
}//End of incrementAge method.
public String getName(){
return "Name: "+name;
}//End of getName method.
public String getPerNo(){
return "Personal number: "+personalNumber;
}//End of getperNo method.
public String getAge(){
return "Age: "+age;
}//End of getAge method.
public String getAdress(){
return "Adress: "+adress;
}//End of getAdress method.
public String toString(){
String toString = "\n>Credentials:\n--------------------------" +
"\n-Name: "+name+"\n-Adress: "+
adress+"\n-Age: "+age+"\n-Personal number: "+personalNumber+"\n";
return toString;
}
}
Re: How can i improve this code?
Why is that I/O code in the Person class?
Re: How can i improve this code?
Quote:
Originally Posted by
Norm
Why is that I/O code in the Person class?
well, before that i put it in the PersonTest class and you told me to move it to "before the constructor", the constructor is in the Person class, so there it went.
Re: How can i improve this code?
Anyway, thanks for your time and effort. I'm going to stick with my first version which worked the way i intended, since i'm not doing any GUI anytime soon (i know nothing about GUIs yet) and i have to write 5 more programs before the deadline (tomorrow). I'll fix this code when i learn some more. Thank you.
Re: How can i improve this code?
Move it to before where you call the constructor.
That would be inside of some method