calling methods from objects (Java) - java

I'm new(ish) to java and I'm making a program for fun that allows you to create different users, login to those users, and make notes. I'm stuck on the user creation part. There is this one line of code that won't work. I have an array called userarr that holds user objects. Inside the object is the user creation method. This is the line of code that takes the variables you type in for the username and password and plugs it into the usercreation method:
userarr[userarr.length+1] = new user.usercreation(username,password);
It says it can't find usercreation method inside the class. But I don't know how to use the usercreation method outside the object and be able to create different named objects.
Here is the entire class:
public class TextGame {
static Scanner scan = new Scanner(System.in);
class user extends TextGame {
String username;
int password;
String[] notes;
public void usercreation(String username, int password) {
this.username = username;
this.password = password;
}
public void login(int password) {
this.password = password;
System.out.println("please type the password to proceed.");
if (scan.nextLine().equals(this.password)) {
System.out.println("logged in. type 'note' to access notes, or 'logoff' to log off this user.");
}
}
}
static user[] userarr;
public static void newuser() {
System.out.println("\n\nType the username for this user.");
String username = scan.nextLine();
System.out.println("Username is now " + username + ". is this what you want? type 'yes' to proceed, or 'no' to enter username again.");
if (scan.nextLine().equals("no")) {
newuser();
}
else {
System.out.println("\n\n type the password for this user. (numbers only.)");
int password = scan.nextInt();
System.out.println("user is " + username + " and password is " + password + " is this what you want?");
if (scan.nextLine().equals("no")) {
newuser();
} else {
userarr[userarr.length + 1] = new user.usercreation(username, password);
}
}
}
public static void main(String[] args) {
System.out.println("Welcome to LINCOLN COMP console OS. Type 'new' to create a new user, type 'log' to log in to an existing user, or type 'exit' to leave.\nif you are asked a yes or no question, if you type something ether than yes or no, it will default to yes.");
String ch1 = scan.nextLine();
switch (ch1) {
case "new":
System.out.println("Initializing user creation method:");
newuser();
break;
case "log":
break;
case "exit":
System.out.println("Goodbye!");
System.exit(0);
break;
}
}
}

Okay, so starting with new user.usercreation(username,password);
usercreation is not a static inner class of user, so you can't create it
usercreation is a method of user which returns void, so you returns nothing, so you can't assign it to anything.
You could...
Create the instance of user, apply the properties and assign it to the array as separate actions
user newUser = user();
newUser.usercreation(username,password);
userarr[userarr.length+1] = newUser;
Equally, you could make usercreation a factory methhod, but I'm trying to keep it simply.
You could...
Based on what you seem to be trying to do, is make the usercreation method into a class constructor, which would make more sense...
class user extends TextGame {
String username;
int password;
String[] notes;
public user(String username, int password) {
this.username=username;
this.password=password;
}
public void login(int password) {
this.password=password;
System.out.println("please type the password to proceed.");
if (scan.nextLine().equals(this.password)) {
System.out.println("logged in. type 'note' to access notes, or 'logoff' to log off this user.");
}
}
}
Then you could just do...
userarr[userarr.length+1] = new user(username,password);
You're also haven't create an instance of the userarr, so you're going to hit a NullPointerException
You should do something like...
userarr = new user[10];
before you try and use it.
This will allow you to maintain ten instances of the user class. You should also check to ensure that you've not exceeded the number of available elements in the array before you try and add new elements.
Have a look at the Arrays Trail for more details
I'd encourage you to have a look at Code Conventions for Java, which make it easier for other people to read your code and make it easier for you to read others

Before you use the usercreation method from a different class, you must first instantiate an object of usercreation class to gain access to it's properties(methods, variables) in a different class.
Example:
UserCreation us = new UserCreation (default constructor parameters);
userarr[userarr.length+1] = us.usercreation(username,password);

You should really be using a constructor:
public user(String username, int password) { // should be named User
this.username = username;
this.password = password;
}
Then you could add a user to an array like so:
userarr[userarr.length+1] = new User("username", 1); // doesn't work!
...Except, this code will fail because you didn't instantiate the array. And even if you had, you can't assign an element to an array like this. Arrays do not automatically re-size themselves, so when you try to add an element like this you will get an ArrayIndexOutOfBoundsException and your program will exit.

Firstly, I'd like to state that you haven't instantiated the userarr array yet. So, I recommend to do that first.
Secondly,new user.usercreation(username,password); usercreation is not a static inner class of user, so you can't create it.
Thirdly, usercreation is a method which returns void in which case you can't assign it to anything.
it seems that you want to invoke this method:
public void usercreation(String username, int password) {
this.username=username;
this.password=password;
}
In order to invoke that method, you must create an object of type user first in order to invoke it.
Example:
user user1 = new user();
user1.usercreation(username,password);
userarr[userarr.length+1] = user1;
However, the easiest way would be to make a constructor to initialise the username and password like below:
public user(String username, int password) {
this.username=username;
this.password=password;
}
Hence you can easily do this:
userarr[userarr.length+1] = new user(username,password);

Related

While trying to use contain() in Arraylist it doesn't find what I'm looking

So I have a class named Student like this:
public class Student {
public int usercounter;
public String username,password,studentname;
Student(String studentname ,String username, String password, int usercounter){
this.studentname = studentname;
this.username = username;
this.password = password;
this.usercounter = usercounter;
}
and I'm trying to write a library login code using Arraylists.
static ArrayList<Student> users = new ArrayList<Student>();
My main menu looks like this:
public static void MainMenu() {
while (menubreak){
System.out.println("ULIS Main Menu\nPlease choose the feature you want to access:\n1-Login\n2-Create User\n3-Delete User\n4-Exit");
gir = Input.nextInt();
Input.nextLine();
switch (gir) {
case 1:
Login();
break;
and I create users like this:
public static void CreateUser() {
while (userbreak) {
System.out.println("You are creating a new User");
System.out.println("Please enter the name of the Student:");
tempStudentname = Input.nextLine();
System.out.println("Please enter a new username:");
tempUsername = Input.nextLine();
System.out.println("Please enter a new password:");
tempPassword = Input.nextLine();
users.add(new Student(tempStudentname, tempUsername, tempPassword, usercounter));
usercounter++;
and my login screen looks like this:
public static void Login() {
System.out.println("Please choose the user type you want to login:\n1-Admin\n2-Student");
giris = Input.nextInt(); Input.nextLine();
switch (giris) {
case 2:
System.out.println("Please enter your username:");
tempUsername = Input.nextLine();
searchUsername = tempUsername;
System.out.println("Please enter your password:");
tempPassword = Input.nextLine();
if(users.contains(searchUsername) && users.contains(tempPassword) ){
System.out.println("User found, logging in now");
UserMenu();
}
else{
System.out.println("User cannot be found, returning to Main Menu");
}
}
}
When I run this it goes to "User cannot be found"
I'm not allowed to use an offline database or smth like that that's why I'm creating usernames on the go and don't store them in something.
What could be the reason it doesn't find the username and password it's looking for? btw I'm a first year student if you can please try to explain things without using complex techniques
You are currently comparing the Student object with the name of the student, but theres an easy fix, suppose we had this code:
List<Student> students = new ArrayList<>();
students.add(new Student("Bob", "password"));
students.add(new Student("Alice","wonderland"));
Then when you get tempUsername and tempPassword from the user input, you could loop through the list and check if there is a student with that name and password:
Student loggedIn = null;
for(Student student : students){
if(student.getName().equals(tempUsername) && student.checkPassword(tempPassword)){
loggedIn = student;
break;
}
}
(Note here I added some getter and setter methods for student, which looks like this now for better encapsulation)
class Student {
private String name;
private String password;
public Student(String name, String password){
this.name = name;
this.password = password;
}
public String getName(){
return name;
}
public boolean checkPassword(String password){
return this.password.equals(password);
}
}
If you're specifically asked to do this with an ArrayList thats all good, but if you can use other data structures you could look into using HashMaps (you could have a HashMap<String,Student> where you could pass in the username of the student and get back the student if its in the HashMap, which would be better time complexity, or better yet, define your own comparable interface and use a HashSet, that way you could make the comparable compare usernames and that would also help prevent users with the same username being added).

How to create an object using user inputs [duplicate]

This question already has an answer here:
user input to create object
(1 answer)
Closed 3 years ago.
I'm working on an exercise, I had to create a "User" class and to create a user using that class' constructor, easy.
The problem comes when the exercise tells you to create a menu which allows the user to create a new user.
I think I have to do something like this
System.out.println("Write the username:");
String username = myObj.nextLine(); // Read user input
And then something like this:
User newuser = new User("%s",username);
But I don't know how to do something like that. I know that syntax is not correct but I guess it should be something like that but I don't know how to do it.
Putting everything together , i think this is what you are looking for:
let's say this is your User class
public class User {
private String username;
public User(String username)
{
this.username=username;
}
public String getUsername()
{
return username;
}
}
this is your Main Class
System.out.println("Write the username:");
Scanner sc = new Scanner(System.in);
String username = sc.nextLine();//line 3
User userobj = new User(username);
What happens is that at line3 you get the user input(let's say username) and you assign the value to a String
if you want to print the username simply do:
in Main class:
//... code
System.out.println(userobj.getUsername());
This may help you.
public class Demo {
public static void main(String[] args) {
String userName = "John"; // or get the username from user
User user = new User(userName);
System.out.println(user.getUserName());
}
}
class User {
private String userName;
public User(String userName) {
super();
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Just use the Scanner class for Console inputs and then the rest is easy. In Java you don't need to use formats like in C.
Scanner sc = new Scanner(System.in);
String username = sc.nextLine();
User user = new User(username);

Storing Objects of Class into an Array

I'm trying to store objects that have a username and password from the class "Driver" into an array list. When I try to print every value in the array to test whether they're being stored, it only prints the last value declared, numerous times. I have tried nearly every other solution on thee forums related to this issue and it just wont work :(
Code below:
package eDepotSystem;
import java.util.ArrayList;
public class Driver {
protected static String driverUserName;
protected static String driverPassWord;
public Driver (String userName, String passWord) {
driverUserName = userName;
driverPassWord = passWord;
}
public static void driverArray() {
ArrayList<Driver> driverList = new ArrayList<Driver>();
Driver driver = new Driver(driverUserName, driverPassWord);
driver.setUserName("driver1");
driver.setPassword("123");
driverList.add(driver);
driver = new Driver(driverUserName, driverPassWord);
driver.setUserName("driver2");
driver.setPassword("321");
driverList.add(driver);
Driver tempDriver = new Driver(driverUserName, driverPassWord);
for (int i = 0; i < driverList.size(); i++) {
tempDriver = driverList.get(i);
System.out.println(tempDriver);
}
}
public void setPassword(String password) {
driverPassWord = password;
}
public static String getUserName() {
return driverUserName;
}
#Override
public String toString() {
return driverUserName + driverPassWord;
}
}
I don't know whether my loop is wrong or the way I'm declaring the objects is wrong? Any help would be grand and thanks in advance!
your field variables should not be static.
It is being shared by all instances of Driver class (ie objects), hence it is printing the last value which you added.
Problem 1:
Your "instance variables" (username and password) are static. Therefore you only have one instance of them. If you print them out you must always get the same value.
Problem 2:
You only add one object. You add it once, change it's values and add it a second time. If you print it out you must get the same values ... even if you remove the statickeywords.
You should instead try something like this:
package eDepotSystem;
import java.util.ArrayList;
import java.util.List;
public class Driver {
private final String driverUserName;
private final String driverPassWord;
public Driver (String userName, String passWord) {
driverUserName = userName;
driverPassWord = passWord;
}
public static void driverArray() {
List<Driver> driverList = new ArrayList<Driver>();
driverList.add(new Driver("drv1", "pw1"));
driverList.add(new Driver("drv2", "pw2"));
for (Driver tempDriver : driverList) {
System.out.println(tempDriver);
}
}
}
The static keyword forces the driverUserName and driverPassWord variables to be instantiated only once in memory. While they are not constants, it makes any further additions to your list reference that first and only instance in memory, hence why it keeps showing the same value.
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

How to put current method's parameter into a list

I have two methods like
public void login(String userName, String password)
{
}
public void login(String userName, String password, Object loginOption)
{
}
and I hope to get all of them soloved in a certain method:
public boolean getThingsDone(Object...vargs)
{
//Do The Real Action
return true;
}
so I have to make different function call:
public void login(String userName, String password)
{
getThingsDone(userName,password);
}
public void login(String userName, String password, Object loginOption)
{
getThingsDone(userName,password,loginOption);
}
Is there any way that I can put different parameter into one List, so I can make the same call
getThingsDone(parameterList);
I have no idea but declare both method into login(String ...vargs), but that will confuse other people use this method.
Is there any one ever meet this problem? Any hint would be appreciated.
You can create a Login class with three attributes: - username, password, loginOption.
public class Login {
private String username;
private String password;
private Object loginOptions;
// Constructors
// public accessors.
}
And in your login method pass Login reference as parameter: -
public void login(Login login) {
}
So, if you want to pass loginOptions, call it like this: -
login(new Login(username, password, loginOptions));
else, just use a 2-parameterized constructor of Login class: -
login(new Login(username, password));
And from login method, call other method like this: -
getThingsDone(login);
Now in that method, check : - if (login.getLoginOptions() != null). If it is null, then do things related to username and password. And if it is not null, then do things related to all of them.
public void login(String userName, String password, Object loginOption)
This method should do the thing and should be able to handle the situation when loginOption is null.
Then you could invoke it as follows:
public void login(String userName, String password) {
login(userName, password, null);
You can pass an array list and use the length to do what ever you need. Why not use overloaded methods and modularize the rest of the code?

How to print the output of an accessor of every instance of a class?

How would you go about creating a class like this:
public class tmUser {
private String Username;
private int wHours;
static int numUsers;
public tmUser(){
Username = "";
wHours = 0;
}
public tmUser(String U, int H){
Username = U;
wHours = H;
}
public void setUsername(String U){
Username = U;
}
public void setwHours(int H){
wHours = H;
}
public String getUsername(){
return Username;
}
public int getwHours(){
return wHours;
}
public static void initnumUsers(){
numUsers = 0;
}
public static int getnumUsers(){
return numUsers;
}
}
and then printing all of tmUser instances Username variable? in maybe a for each loop? I'm hoping for something like:
for each(tmUser){
System.out.println(Username);
}
This is for a menu in a program which displays all created users usernames.
You almost had it:
List<TmUser> tmUsers = ...
for(TmUser user : tmUsers) {
System.out.println(user.getUsername());
}
You would also want to capitalize tmUser into TmUser.
When you create a tmUser add it to a collection like
List<TmUser> tmUsers = new ArrayList<TmUser>();
TmUser tmUser = new TmUser(username, hoursWorked);
tmUser.add(tmUser);
// later
for(TmUser tmUser: tumUsers)
System.out.println(tmUser.getUsername());
You need to store all of tmUser instances somewhere first. You could do it this way:
public class tmUser {
...
public static List<tmUser> USERS = new ArrayList<tmUser>();
public tmUser() {
...
USERS.add( this );
}
and then printing:
for (tmUser user : tmUser.USERS) {
System.out.println(user.getUsername());
}
The 3 current answers are basically the same. Just wanted to add that if the class defined a toString() that returned the user name, it would not be necessary to add the .getUsername() method call, since System.out.println(Object) will automatically call the toString() method.
Whether this could work for your use case is debatable. The toString() method would normally provide more data on the object.
As the answers already posted indicate, this would involve maintaining some sort of data structure that holds references to all instances of tmUser (e.g. a List<tmUser>).
This would mean that a reference to each and every instance ever created will always be held there, they will never be garbage collected. You could explicitly remove them when you decide an instance is no longer needed, but then you would have to keep track of the life cycle of all instances, and basically end up doing memory management yourself.

Categories

Resources