How to create an object using user inputs [duplicate] - java

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);

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).

calling methods from objects (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);

Can't call a method from a separate class in Java

making a little mini blog application, just setting up the places to hold the data. I have 3 classes one for the post one for the user and one for the test, which I named Blog. when I try to call the getName(); method in the Blog class it won't run it keeps saying it needs a string, but I made an array of user objects, and input a string for the userName spot, and it still isn't working.
public class Blog
{
public static void main(String []args)
{
User[] userList = new User[3];
userList[0] = new User("what.com", "TheLegionCrab", "Jake Parham", "jparham#gmail.com");
userList[1] = new User("huh.com", "RaggleFraggle", "Brett Hawkins", "bhawkins#gmail.com");
userList[2] = new User("buh.com", "SeanBeast", "Sean Sweeney", "ssweeney#gmail.com");
for(int counter = 0; counter<userList.length; counter++)
{
User.getName();
}
}
}
public class User
{
private String url;
private String userName;
private String realName;
private String email;
public User(String url, String userName, String realName, String email)
{
this.url = url;
this.userName = userName;
this.realName = realName;
this.email = email;
}
public void getName(String userName)
{
System.out.println(userName);
}
}
public void getName(String userName)
{
System.out.println(userName);
}
Here your function require a String. That is why it need string to run. If you want to print the userName of the current User object in your loop then use this.
public void getName()
{
System.out.println(this.userName);
}
This refer to current User object in your loop.
Now back to your loop.
for(int counter = 0; counter<userList.length; counter++)
{
User.getName();
}
You use User class meanwhile you create variable as
User[] userList = new User[3];
To print from your var, you should use the var.
for(int counter = 0; counter<userList.length; counter++)
{
userList[counter].getName();
}
You need to access a User instance from your userList array (or get an instance some other way) to call the method on (and either assign it to a variable and use it or just print it). In Java, array access is performed with []. Something like
for (int counter = 0; counter < userList.length; counter++)
{
System.out.println(userList[counter].getName());
}
You could also you an enhanced for loop (for-each loop) like
for (User user : userList) {
System.out.println(user.getName());
}
Also, I don't think getName should be shadowing the class name field. You wanted something like,
public void getName()
{
System.out.println(this.userName);
}
or following the Java practice of returning the value in a getter (and to fix my examples above)
public String getName()
{
return this.userName;
}
That's because you specified that the getName method in the User class takes a String as the argument. You did that here:
public void getName(String userName)
{
System.out.println(userName);
}
So it's working exactly they way you have told it to.
But really, you want "setName()" to take a String arg, and "getName()" to take no arg. It should look like this:
public void setName(String new_userName)
{
username = new_userName;
}
public void getName()
{
System.out.println(userName);
}
But even then, I'd say that your method names are a bit ambiguous: should I use "getName" to get the username, or to get the realName?
(did you spot the error?)
It looks like what you want is to print the name of the user instance instead of the parameter to the getName method. Try this defining the method like this:
public void getName()
{
System.out.println(this.userName);
}
and in the main method:
User[] userList = new User[3];
userList[0] = new User("what.com", "TheLegionCrab", "Jake Parham", "jparham#gmail.com");
userList[1] = new User("huh.com", "RaggleFraggle", "Brett Hawkins", "bhawkins#gmail.com");
userList[2] = new User("buh.com", "SeanBeast", "Sean Sweeney", "ssweeney#gmail.com");
for(int counter = 0; counter<userList.length; counter++)
{
userList[counter].getName();
}
Issues:
a) Calling getName() without any object i.e as a static function. Instead use the objects created and call it as:
userList[counter].getName();
b)Creating User objects with the name (in constructor) and also calling getName with argument i.e userName. This is wrong/not needed. When you created the object, you have already informed the object about the userName. So have a clean getter without any argument.
getName()
The code:
public class Blog
{
public static void main(String []args)
{
User[] userList = new User[3];
userList[0] = new User("what.com", "TheLegionCrab", "Jake Parham", "jparham#gmail.com");
userList[1] = new User("huh.com", "RaggleFraggle", "Brett Hawkins", "bhawkins#gmail.com");
userList[2] = new User("buh.com", "SeanBeast", "Sean Sweeney", "ssweeney#gmail.com");
for(int counter = 0; counter<userList.length; counter++)
{
userList[counter].getName(); # Correct this to use the created objects.
}
}
}
public class User
{
private String url;
private String userName;
private String realName;
private String email;
public User(String url, String userName, String realName, String email)
{
this.url = url;
this.userName = userName;
this.realName = realName;
this.email = email;
}
public void getName() #Remove the argument.
{
System.out.println(this.userName);
}
}
You have to make the object of the User class before calling else your User class should be static to call it direct.
for(int counter = 0; counter<userList.length; counter++)
{ User obj = new User();
obj.getName();
}
else
public static User
{
public User(String url, String userName, String realName, String email)
{
this.url = url;
this.userName = userName;
this.realName = realName;
this.email = email;
}
public void getName(String userName)
{
System.out.println(userName);
}
}

How to change the name of a object using user input?

how would i change the name of a object using user input.
for ex. i am asking the user to input their id as a string.
i want to then use that to create a constructor.
ex.:
RefUnsortedList<Patients> NewList = new RefUnsortedList<Patients>();
Patients entry1=null;
System.out.println("Please enter patient's ID: ");
String TargetID = scan.next();
I want to set
Patients entry1 = null;
to make it
Patients "the user input here" = null;
There are no dynamic variables in java, they have to be declared in the source code.
You could try using a Map and assigning each instance of a variable a key.
Map patientMap = new HashMap();
patientMap.put("entry1", new Patients());
patientMap.put("the user input here", new Patients());
Then when you want to retrieve the patient you can use:
Patients patient = patientMap.get("the user input here");
What you actually want to do is:
Map<String, Patient> patients = new HashMap<>();
patients.put("entry1", /* [insert Patient object here] */);
Things to note:
The class to represent a patient should be named Patient, not Paitents. A class should be named for its instances, not their collection.
It is meaningless to set the value in a map to null, unless you are using a special type of map that allows a null key (and makes it meaningfully different from not having an entry for that key).
I am assuming you are doing something like this:
Your Patient Class:
public class Patient {
private String patientID;
public Patient(String patientID) {
this.patientID = patientID;
}
public String getPatientID() {
return patientID;
}
public void setPatientID(String patientID) {
this.patientID = patientID;
}
}
...and your class that you are using for running the console:
public class Main {
public Main() {
}
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("System is ready to accept input, please enter ID : ");
String ID = console.nextLine();
Patient patient = new Patient(ID);
//do some fancy stuff with your patient
}
}
This would be a very basic example.
As you are learning to code, be sure to really think about how to name your classes. Calling your class "Patients" would make me expect you are holding a collection of "Patients" inside each instance of this java class, rather than a single "Patient" per instance.
Regarding the latest answers including Maps, the updated "Main" class could look like this:
public class Main {
static Map<String, Patient> patients = new HashMap<String, Patient>();
public Main() {
}
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("System is ready to accept input, please enter ID : ");
String id = console.nextLine();
patients.put(id, new Patient(id));
}
}

java username and password varification [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
could any one help me to find problem on this code username and password verification.
username and password are predefined just checking this
package org.test;
import java.util.*;
class User{
public String username;
public String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void chackLogin(){
Auth a = new Auth();
a.authentication();
}
}
class Auth{
User u;
// username and pass
String auser="admin";
String apass="admin";
public void authentication(){
if((u.username==auser) && (u.password==apass))
{
System.out.println("Login Succseeful sor the user "+" "+auser);
}
else{
System.out.println("incorrect username or password");
}
}
}
public class UserAuth {
public static void main(String[] args) {
//scan Username
Scanner user=new Scanner(System.in);
String usern= user.next();
//scan password
Scanner pass=new Scanner(System.in);
String passw= pass.next();
//object of class USEr
User u =new User();
//set user and pass
u.setUsername(usern);
u.setPassword(passw);
u.chackLogin();
}
}
String comparison in java are done using equals method and not using == operator. Modify this condition :
if((u.username==auser) && (u.password==apass))
to
if((u.username).equals(auser) && (u.password).equals(apass)))
equals compares the contents of the two strings whereas == checks whether two references point to the same memory object. Learn more about the difference on this related post: Java String.equals versus ==

Categories

Resources