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.
Related
I am have been trying to solve this challenge for a while now. I am a JavaScript developer but have been trying out Spring Boot and Java and am running into an issue. In the below code I need to figure out how to write the #RestController logic to return JSON from the list of users created below in the User class. I am not sure how to go about doing that since this is all new to me.
package usersExample;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
#RestController
public class UsersController {
/* Please insert your code here to make the tests pass */
}
#Service
class UserService {
public List<User> all() {
List<User> users = new ArrayList<User>();
users.add(new User("Bob"));
users.add(new User("Christina"));
users.add(new User("Steve"));
return users;
}
}
class User {
private final String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Since you're using #RestController, the return value is already a JSON (spring-boot does the conversion without adding additional dependencies because it already include the Jackson library).
You can simply create a method in your controller which will return a List of users. One comment about your code: use proper method names like findAll() instead of all().
#GetMapping("/find-all")
public List<User> findAll()
{
return userService.findAll();
}
P.S.: And in case that the code you've added is the same with the one you're running, I suggest you to create separate classes for User and UserService.
EDIT: The conversion of a simple object into a JSON object is done using getters. How is it working? Let's take your example:
class User {
private final String name;
public String getName() {
return name;
}
}
The converter will look for methods starting with the get keyword and set everything after that as an attribute name with first letter converted to lower case, this means that the ONLY attribute (because you have only 1 getter) will look like this: name : -value here-.
Now you may be asking some questions like :
1)
Q: What happens if you change your getName() method to getname() ?
A: Will work the same
2)
Q: What happens if you don't provide a getter to a field?
A: The field won't be converted to a JSON property
3)
Q: What happens if you change getName() method to getMyName() ?
A: The attribute name will be myName: -value-
So, if these have been said, if you want to change your JSON structure, there are many solutions:
1) Change the getter names (not really recommended)
2) Use the #JsonProperty annotation. E.g.:
private String name;
#JsonProperty("name")
public String thismethodwontworkwithoutjsonproperty() {
return this.name;
}
3) Create a DTO object UserDTO and return this instead of User. And in your controller you can convert the user to an userDTO object.
public class UserDTO {
private String fullName;
//getter; setter;
}
and
public class User {
private String firstName;
private String lastName;
//getter;setter;
}
And eventually, you make the conversion like this:
#GetMapping("/getUser")
public User returnUser() {
User user = new User();
user.setFirstName("Stack");
user.setLastName("Overflow");
UserDto userDto = convertUser(user);
return userDto;
}
private UserDTO convertUser(User user) {
UserDTO userDTO = new UserDTO();
userDTO.setFullName(user.getFirstName() + " " + user.getLastName());
return userDTO;
}
But I would suggest you to structure your application and add a facade layer which will make this conversion instead of creating convertUser() method in the controller.
Output:
{
"fullName":"Stack Overflow";
}
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.
I have a situation where I define security roles for an organization. The choices are a set of known enumerated default values, and the possibility of any number of custom role. The roles define the permissions the employees have in the organization. For example, a user can be;
public enum Role
{
Owner, Administrator, User, Guest;
}
However, the organization could also want its own custom roles (e.g. A PowerUser). I am looking for the best way to declare an object that has a known enumerated list of values (thats an enum) but with the possibility of provide any number of custom values (thats a class).
A naive approach would be the following (adding a custom enum value):
public enum Role
{
Owner, Administrator, User, Guest, Custom;
public BaseRole asRole()
{
//switch statement returning the BaseRole depending on the enum value.
}
}
public class BaseRole
{
Set<Permission> permissions;
}
The problem with this option is that the glue code will became very verbose if the enum value custom is selected. Since the custom value which holds all possible custom role would behave differently that the other values, every function that accepts a Role will need special glue to handle custom.
Ideally, something like this would probably be the best:
public enum Role
{
Owner, Administrator, User, Guest, Set<Custom>;
}
edit:
for reference, the user class would be
public class User
{
Set<Role> roles;
}
A possible solution would be to look back in pseudo-enum implementations in the pre enum Java versions. E.g.:
public class Role {
public static final Role OWNER = new Role("OWNER");
public static final Role ADMIN = new Role("ADMIN");
public static final Role USER = new Role("USER");
public static final Role GUEST = new Role("GUEST");
private String name;
// getter, setter, constructor, toString(), hashCode(), equals()
}
So whenever a Role is required, you can use the final fields:
Role r = Role.OWNER;
And still define custom ones:
Role r = new Role("Cook");
With some caution, it may even allow for == equality checking between a variable and the predefined values, but I would advise against it (use equals() always).
Maybe what you're looking for is an EnumSet?
http://docs.oracle.com/javase/7/docs/api/java/util/EnumSet.html
This is the solution I went with.
public interface Role
{
String getName();
}
public enum StandardRole implements Role
{
Owner, Administrator, User, Guest;
#Override
public String getName()
{
return this.name();
}
}
public class CustomRole implements Role
{
private String name;
public CustomRole(String name)
{
this.name = name;
}
#Override
public String getName()
{
return this.name;
}
}
public class User
{
Set<Role> roles;
}
I have 2 classes which I am making in blueJ- one called User and the other UserGroup. My user class looks like this:
public class User{
public enum UserType{
ADMIN, EDITOR, USER;
}
public String id;
public UserType userPermissions;
public 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 like this so far:
import java.util.*;
public class UserGroup{
private static ArrayList<User> UserGroup= new ArrayList<User>();
public static void add(String username, UserType userType, String name){
UserGroup.add(new User(username, userType,name));
}
}
My problem is when I try to compile UserGroup it says "cannot find symbol- class UserType". I am trying to create an arraylist in UserGroup of Users created in the User class. Where am I going wrong?
UserType is an inner class of User:
public class User {
// inner
public enum UserType {
ADMIN, EDITOR, USER;
}
If you want to use it in UserGroup there are two things you can do. First you can import it and then you can access it from UserGroup:
import mypackage.User.UserType;
public class UserGroup {
Or without importing it you can access it from UserGroup with a dot:
User.UserType type = User.UserType.ADMIN;
You could put it in its own class but in my opinion making it an inner in User makes sense because it is innately an attribute of User.
Also one thing to note is that normally the rules for inner classes are a bit different than regular classes. Normally inner classes are instance members, that is the inner class is owned by the instances of the outer class, not the outer class itself. To access an inner class like Outer.Inner you have to declare the inner class as static. Enums are static by default so you don't have to declare them as such.
The enum UserType must be a separate class; at the moment it's an inner class accessible to User class only and it is not accessible to the UserGroup class. This can be achieved by using the IDE to create a new enum called UserType while removing e inner class enum that has been used within User.
Alternatively, you could use he import as has been mentioned:
import packagename.User.UserType;
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);