Making the arraylist get method work and other problems - java

I am coding in blueJ. My objectives are this: 1)Write a User class
A User:
has a username e.g 'fj3'
has a userType which can be: 'user', 'editor' or 'admin'
has a name e.g 'Francis'
has a constructor which takes the username, userType and name as parameters
has a getUsername() method
has a getUserType() method
has a getName() method
has a setUserType() method which takes one of the user types as a parameter
2)Write a UserGroup class
The UserGroup class must have an ArrayList of Users.
Write a constructor for the UserGroup class. It should instantiate the ArrayList.
In UserGroup write a method called .addSampleData() which creates 10 Users and using the ArrayList's add() method put the 10 new User objects into the ArrayList.
In UserGroup write a getUser method which takes an int as a parameter and returns the User in that slot of the ArrayList.
In UserGroup write a printUsernames() method in UserGroup:
Using an enhanced for loop (see above), loop through the ArrayList and print the username and userType of each user in the ArrayList.
What I have so far is:
package user;
public class User{
public enum UserType{
ADMIN, EDITOR, USER;
}
private String id;
private UserType userPermissions;
private String actualName;
public User(String username, UserType userType, String name){
id = username;
userPermissions = userType;
actualName= name;
}
public String getUsername(){
return id;
}
public UserType getUserType(){
return userPermissions;
}
public String getName(){
return actualName;
}
public void setUserType(UserType input){
userPermissions = input;
}
}
And my UserGroup class:
package user;
import java.util.*;
import user.User.UserType;
public class UserGroup{
private ArrayList<User> people;
public UserGroup(){
people = new Arraylist<User>();
}
public static void addSampleData(String username, UserType userType, String name){
people.add(new User(username, userType,name));
}
public User get(int){
return User;
}
public void printUsernames(){
for (User user: groupArray){
System.out.printf("%s %s\n", user.getUsername(), user.getuserType);
}
}
}
This is obviously far from being complete but I am completely stuck. My first problem is that I am unsure how to write the get method for this. Please help me with this!! I think my User class is fine but my UserGroup class is nowhere near completing all the objectives and I don't know how to do them!!

Looks good so far, some corrections:
The addSampleData()method should not be static, as it uses a non-static member of the class. The request also states it to add the sample data itself.
The getUser() is pretty straight forward then.
The printUsernames()method uses an unknown member.
public void addSampleData() {
people.add(new User("pe3", UserType.ADMIN,"Peter"));
people.add(new User("u987", UserType.EDITOR,"Udo"));
people.add(new User("frank123", UserType.USER,"Frank"));
// repeat ...
}
public User getUser(int idx) {
return people.get(idx);
}
public void printUsernames(){
for (User user: people){
System.out.printf("%s %s\n", user.getUsername(), user.getuserType);
}
}
In a main method then:
UserGroup grp = new UserGroup();
grp.addSampleData();
grp.printUsernames();
User u1 = grp.getUser(0);

Related

How to cast one object into another

I am a beginner in Java and have below 2 Beans/POJOS in my existing company application:
User
public class User {
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
Employee
public class Employee {
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
I want to cast User to Employee because in the application I would be receiving the User object in the one of the methods which is used for persisting into the database using hibernate3 xml mapping method. HIbernate mapping exists for the Employee object and not for User. Hence I tried the conversion using the below concept that everything in java is an object but still it is giving the RuntimeException of ClassCastException :
User u = new User(12,"johnson","pam",new Date());
Object o = u;
Employee e=(Employee)o;
Is there any other way to solve this problem? There is no option to change the existing class hierarchies or include any additional inheritance structure.
You cannot cast objects at all in Java. You can cast a reference, to a type implemented by the referenced object.
What you can do is convert from one object to a new object. If you cannot modify the classes, you can write an external converter. For example:
public class EmployeeFactory {
public static Employee toEmployee( User user ) {
Employee emp = new Employee();
emp.setUserId( user.getUserId() );
emp.setUserName( user.getUserName());
return emp;
}
}
You can't cast user object to an employee object as they don't have any relation. You should have some Mapper class which will map a User object to Employee Object.
class UserToEmployee{
public Employee map(User user){
Employee e = new Employee();
e.setUserId(user.getUserId());
// so on set all the required properties
return e;
}
}
Then use it like:
User u = new User(12,"johnson","pam",new Date());
UserToEmployee mapper = new UserToEmployee();
Employee e = mapper.map(u)
Because Employee and User is completely two different object, so you cannot cast like your case
A simple example
User
public class User {
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
Employee
public class Employee extends User {
//constructor
}
Then you can do this
Employee e = new Employee();
Object o = e;
User = (Employee) o;
Of course, In this case, you cannot do the opposite way: cast User to Employee
Hope this little example help you understand clearly about the case.
In java, an easy way to think about casting objects is: "Am I lying?"
Ie if I cast the User to Employee, I'm saying the User is an Employee. Am I lying? If so, the cast will work. If not, then it wont. Now, according to your logic, you want all Employees to be Users. To establish an "is-a" relationship, you can use the word "extends"
class User{
//Your things
}
class Employee extends User{
//More employee-specific things
}
Now if you do
User john=new User(//args);
You can do
if(john instanceof Employee){//Make sure john is an employee
Employee johnEmployee=(Employee)john
}
All casting is is relabeling an object. But you can't lie about anything that isn't established when the object is made.

How to assign properties to a user in an Array List?

So far I have created an Array List which only currently consists of one user. For my assignment, I have been asked to print out properties for that user such as its username and userType. As far as I aware I have created an enhanced for loop that would print out these properties if only they were assigned. My question is how would I go about assigning these properties to my user? I have created a UserGroup class in which the array list resides in and a User class in which some details about the User is specified however I am not quite sure if the User class is correct for what I am trying to achieve. Here is the code for both classes:
UserGroup:
package main;
import java.util.ArrayList;
public class UserGroup {
ArrayList<User> userGroup = new ArrayList<>();
User userOne;
public void addSampleData(String username, String userType, String name) {
userGroup.add(new User("LeeB", "Staff", "Lee"));
}
public User getUser(int index) {
return userGroup.get(0);
}
public void printusername(){
for (User x : userGroup)
System.out.println(x);
}
}
User:
package main;
class User {
String username;
String userType;
String name;
User(String username, String userType, String name) {
this.username = username;
this.userType = userType;
this.name = name;
}
public String getUsername() {
return username;
}
public String getUserType() {
return userType;
}
public String getName() {
return name;
}
public String setUserType(String admin) {
return userType = admin;
}
}
Main method:
package main;
public class Main {
public static void main(String[] args) {
for (int counter=2; counter<=40; counter+=2) {
System.out.println(counter);
}
System.out.println("For loop complete.");
int counter = 1;
int increment = 2;
int loopexeccounter = 0;
while (counter <= 500) {
loopexeccounter = loopexeccounter + 1;
System.out.println(counter);
counter = counter + increment++;
}
System.out.print("This loop iteratted "+loopexeccounter+" times.");
}
public Main() {
UserGroup userGroupObject = new UserGroup();
System.out.println(userGroupObject.getUser(0));
}
}
Ignore everything above the latest method, it's just some examples of loops that they wanted us to print out.
Updated version, no errors but user(0) isn't being printed out.
So far I have created an Array List which only currently consists of one user.
Actually, user0 is never assigned. It's null, so you're only going to be adding null into the list.
You do not need user0 variable.
ArrayList<User> userGroup = new ArrayList<>();
User userOne;
public void addSampleData(String username, String userType, String name) {
userGroup.add(new User(username, userType, name));
}
Then,
public User getUser(int index) {
return userGroup.get(index);
}
If you want the first user, call that method with 0 as the parameter.
As far as this is concerned, it's fine, but see How do I print my Java object without getting "SomeType#2f92e0f4"?
public void printusername(){
for (User x : userGroup)
System.out.println(x);
}
Alternatively, if you just want x's username, then print that instead of the entire object
Slightly more advanced option, since the Group essentially is a list of users.
public class UserGroup extends ArrayList<User> {
Or, you don't really need that class unless you add more specialized methods than add, get, and print

How to reference variables in a new class?

I'm writing a program which consists of multiple classes. One class is called "User" and the other one is called "userGroup". I'm trying to import a variable which is contained within a constructor from the User class and use it in the userGroup class.
I've tried the following code:
User userRetrieve = new User();
userRetrieve.User();
This code doesn't seem to work, although I have seen in various tutorials that this is how you would retrieve data from another class. The second line has ".User()" because the constructor is also called User but I am not sure if this is correct and even if it was the initial problem of the program not recognizing the first line would still remain.
I'll show the code form both classes for extra information which may show where I have gone wrong:
User class:
public class User {
String username;
String userType;
String name;
public User() {
username = "x";
userType = "y";
name = "z";
}
public String getUsername() {
return username;
}
public String getUserType() {
return userType;
}
public String getName() {
return name;
}
public String setUserType(String admin) {
return userType = admin;
}
}
userGroup class:
import java.util.ArrayList;
public class userGroup {
String User;
ArrayList<User> userArray = new ArrayList<>();
Integer user0;
public void addSampleData() {
userArray.add(new User());
}
public void getUser(User user0) {
user0 = userArray.get(0);
}
public void printusername() {
System.out.println(user0.getUserName()); // x
}
}
I'm trying to use the username and userType variables in the constructor from the User class.
P.S Apologies for any formatting/indentation errors.
You have misunderstrood some concepts. Firstly the User() method is the constructor so when you do User user = new User() that method is called. I suggest this change to your user class
public class User {
private String username;
private String userType;
private String name;
// Use constructor to pass data to your class
public User(String username, String userType, String name) {
this.username = username;
this.userType = userType;
this.name = name;
}
public String getUsername() {
return username;
}
public String getUserType() {
return userType;
}
public String getName() {
return name;
}
public String setUserType(String admin) {
return userType = admin;
}
}
Now you can create your array and add a user, then retrieve its information
List<User> users = new ArrayList<User>();
users.add(new User("x", "y", "z"));
users.get(0).getUsername(); // returns "x"
Make a list of users
List<User> users = new ArrayList<User>()
Add a user
users.add(new User());
Get a user (lists and arrays are zero-indexed)
User user0 = users.get(0);
Print some properties
System.out.println(user0.getUserName()); // x
You could use the get methods you created in the constructor class?
So if you want to get the username and the userType just create a new variable using the get method
User userRetrieve = new User();
String username = userRetrieve.getUsername();
String userType = userRetrieve.getUserType();
Or alternatively you could just directly access the variables:
User userRetrieve = new User();
String username = userRetrieve.username;
String userType = userRetrieve.userType;
User userRetrieve = new User();
On this line you are instantiating a new object of type Person,
you do this by calling the constructor associated with this particular class.
After you have done this it is possible to acces parameters by calling the various methods you have defined in the Person class. So in your case you should use userRetrieve.getUsername() and so on.. you will however need to declare a variable in the calling class to store these values in.

Not printing required result

When trying to test with SOAP UI..I coudn't get correct output for :
public String registerUserByuser(String user)
public String getAllUsers(String userNames)
User.java
package com.ws.entity;
public class User implements java.io.Serializable{
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
private String userName;
private int userId;
}
===============================================================================
RegistrationService.java
package com.ws.Service;
import com.ws.entity.User;
public interface RegistrationService {
String registerUserByuser (String user);
User getuserNameById(int Id );
String getAllUsers (String userNames);
}
===============================================================================
RegistrationServiceImpl.java
package com.ws.test;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.ws.Service.RegistrationService;
import com.ws.entity.User;
#WebService(name = "UserWS", serviceName="RegService", portName = "CustomerPort", targetNamespace = "http://www.reg.com")
public class RegistrationServiceImpl implements RegistrationService {
#WebMethod
#Override
public String registerUserByuser(String user) {
// TODO Auto-generated method stub
User u = new User();
u.setUserId(555);
u.setUserName("Keith");
return user;
}
#WebMethod
#Override
public User getuserNameById(int Id) {
// TODO Auto-generated method stub
User a = new User();
a.setUserId(888);
a.setUserName("Seth");
return a;
}
#WebMethod
#Override
public String getAllUsers(String userNames) {
return userNames;
// TODO Auto-generated method stub
}
}
Requirement is to develop Bottom Up WebServices:
UserRegistration - Interface
method 1 - registerUser that takes user as input and sends String as output
method 2- getUser that takes id as input and returns back user object
method 3 - getAllusers that returns list of users back to user
Am I writing code in incorrect way?
Your code seems more a mockup than an actual implementation. You are hardcoding the user you return in the getuserNameById method and you also have the mistake pointed out by Invexity in the getAllUsers method.
You need some form of persistence. For prototyping, you could just add a List attribute to your class, to store the users you create. Something like:
private List<User> users = new ArrayList<User>();
and in the registerUserByUser method do something like:
this.users.add(user);
Finally, in the getAllUsers method, you could just:
return this.users;
However, if this is some sort of mockup or test, it would be alright I guess. But if you are building production code, you need to read some more about webservices, persistence and security (given the fact that your domain is about users). This code is definitely not suitable for production for many reasons (hardcoding, lack of actual persistence, security of data, to name a few).

Unable to import my own class into another class

I am coding in blueJ. My objectives are this:
1)Write a User class
A User:
has a username e.g 'fj3'
has a userType which can be: 'user', 'editor' or 'admin'
has a name e.g 'Francis'
has a constructor which takes the username, userType and name as parameters
has a getUsername() method
has a getUserType() method
has a getName() method
has a setUserType() method which takes one of the user types as a parameter
2)Write a UserGroup class
-The UserGroup class must have an ArrayList of Users.
Write a constructor for the UserGroup class. It should instantiate the ArrayList.
In UserGroup write a method called .addSampleData() which creates 10 Users and using the ArrayList's add() method put the 10 new User objects into the ArrayList.
In UserGroup write a getUser method which takes an int as a parameter and returns the User in that slot of the ArrayList.
In UserGroup write a printUsernames() method in UserGroup:
Using an enhanced for loop (see above), loop through the ArrayList and print the username and userType of each user in the ArrayList.
What I have so far is:
package user;
public class User{
public enum UserType{
ADMIN, EDITOR, USER;
}
private String id;
private UserType userPermissions;
private String actualName;
public User(String username, UserType userType, String name){
id = username;
userPermissions = userType;
actualName= name;
}
public String getUsername(){
return id;
}
public UserType getUserType(){
return userPermissions;
}
public String getName(){
return actualName;
}
public void setUserType(UserType input){
userPermissions = input;
}
}
And my UserGroup class:
package user;
import java.util.*;
import user.User.UserType;
public class UserGroup{
private ArrayList<User> people;
public UserGroup(){
people = new Arraylist<User>();
}
public static void addSampleData(String username, UserType userType, String name){
People.add(new User(username, userType,name));
}
public String getUser(int list){
return User;
}
public void printUsernames(){
for (User user: groupArray){
System.out.printf("%s %s\n", user.getUsername(), user.getuserType);
}
}
}
This is obviously far from being complete but I am completely stuck. My first problem is that "for (User user : groupArray)" is giving me the error illegal start of type. Please help me with this!! I think my User class is fine but my UserGroup class is nowhere enar completing all the objectives and I don't know how to do them!!
The specification requires a UserGroup's list of users to be
instantiated within the constructor. Thus, it should be not be
static but an instance variable:
public class UserGroup {
private ArrayList<User> people;
public UserGroup() {
people = new ArrayList<User>();
}
// ...
}
This way, you can create multiple UserGroup instances, each having their own list of users. With a static variable, this would not be possible.
Your getUser(int) method does not do what it is supposed to do and
will not compile. You are returning the type User there instead of
a specific User instance.
The enhanced for loop you use for printing user names is a free floating block of code. It should be inside the method printUsernames() as prescribed by your specification.
Your User class will work fine, but its instance variables should be private instead of public.
To resolve your import issues, put your User class into a package, e.g. user, and have UserGroup import User.UserType (the "User." part is needed since UserType is an inner class within User) from this package.
package user;
public class User{
// ...
}
package user;
import java.util.*;
import user.User.UserType;
public class UserGroup{
// ...
}
To iterate through the users in the arraylist, your enhanced for loop should be like this:
for (User user: groupArray)
System.out.printf("%s %s\n", user.getUsername(), user.getuserType);
EDIT:
To adhere more effectively to the question and to be more conventional, the ArrayList should be declared then instantiated after.
private static ArrayList<User> UserGroup;
public UserGroup() {
UserGroup = new ArrayList<>();
}
Your use of "Package" in your import seems suspicious:
import package.User.UserType;
as usually this would be
import User.UserType;
or actually more commonly:
import user.UserType;
since package names by convention should begin with a lower-case letter.
In the future, please be sure to include your package statements with your code if the package name is relevant to the question.

Categories