java username and password varification [duplicate] - java

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 ==

Related

Trying to transfer data from one jFrame to another jFrame with the help of a Java Class

I am trying to transfer a email and password data taken in one jFrame to another using a separate java Class. All are in same Package. Any help is much appreciated, this is my first question so don't know the proper specifics to mention so let me know if you require.
LoginForm.java (1st jFrame)
Part where the data manipulation is present here String mail,pass; have email and password data
if(op==true) {
JOptionPane.showMessageDialog(null, "Login Successful!", "WebApp Database Login",
INFORMATION_MESSAGE);
DataTransfer dt=new DataTransfer(); // Setting instance of DataTransfer class
//to pass on Mail and Password details
dt.setEmail(mail);
dt.setPassword(pass);
InfoDisplay id=new InfoDisplay();
id.setVisible(true);
}
DataTransfer.java
public class DataTransfer {
private String loginEmail;
private String loginPassword;
public String getEmail() {
return loginEmail;
}
public String getPassword() {
return loginPassword;
}
public void setEmail(String email) {
loginEmail=email;
System.out.println("Stored Mail: "+loginEmail);
}
public void setPassword(String password) {
loginPassword=password;
System.out.println("Stored Pass: "+loginPassword);
} }
InfoDisplay.java (2nd jFrame)
//Constructor
public InfoDisplay() {
initComponents();
//Displaying Current Date and Time
Calendar cl=Calendar.getInstance();
String datetime=cl.getTime().toString();
jLabel5.setText(datetime);
//Getting the Stored details of Mail and Password from DataTransfer class
DataTransfer dt=new DataTransfer();
String finalEmail=dt.getEmail();
String finalPass=dt.getPassword();
System.out.println("Email: "+finalMail);
System.out.println("Password: "+finalPass); }
I have used Print commands to just check whether they are assigned properly or not. I am running the program from only LoginForm.java, and the data gets stored in DataTransfer.java but it shows Email: NULL and Password: NULL values in InfoDisplay()
I got it working with this....
LoginForm.java
public class LoginForm {
public static void main(String[] args) {
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setEmail(mail);
dataTransfer.setPassword(pass);
InfoDdisplay infoDdisplay = new InfoDdisplay(dataTransfer);
}
}
InfoDisplay.java
public class InfoDisplay {
public InfoDisplay(DataTransfer dt) {
//Displaying Current Date and Time
//Getting the Stored details of Mail and Password from DataTransfer class
String finalEmail = dt.getEmail();
String finalPass = dt.getPassword();
System.out.println("Email: " + finalEmail);
System.out.println("Password: " + finalPass);
}
}
DataTransfer.java
public class DataTransfer {
private String loginEmail;
private String loginPassword;
public String getEmail() {
return loginEmail;
}
public String getPassword() {
return loginPassword;
}
public void setEmail(String email) {
loginEmail=email;
System.out.println("Stored Mail: "+loginEmail);
}
public void setPassword(String password) {
loginPassword=password;
System.out.println("Stored Pass: "+loginPassword);
}
}

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

Java input char to array that is accessed from another class

Just to be transparent, this is an assignment for a class I am taking. I don't want someone else to do this for me, I'm just asking for a little nudge in the right direction. In this assignment, I need to grade a test that the user takes. The answer key is given. The thing that I am stuck on is how to input the char values into the array Driver.setAnswerSet. I've extensively searched the material given in the class, and I have tried many different possible solutions in Eclipse to solve this problem I'm having. To be exact, I'm not sure exactly how to input the values into the array. Putting the values into a regular array that is initialized in the same class is something I can do, but the addition of calling the array is becoming the end of me here. How would I go about placing input from the user into the array in question when it's being called from the other class? The current error I have is "The method setAnswerSet(char[]) in the type SU2018LAB6_DriverCandidate_Wayne is not applicable for the arguments (char)." Again, all I'm asking for is a piece of advice or push in the right direction here. Any help or assistance would be greatly appreciated. I also really do apologize if I'm asking what seems to be a stupid question.
This is the data class file that I have.
public class SU2018LAB6_DriverCandidate_Wayne {
private char[] keySet = {
'A','C','B','B','D','B','C','D','A','B',
'C','A','B','C','A','B','A','C','A','D',
'B','C','A','D','B'
};
//the answer key to be graded off of
private char[] answerSet;
//the answer key that is inputted by the user
private String lastName;
private String firstName;
private String socialNumber;
private String phone;
private String address;
//the getters and setter made by Eclipse
public char[] getKeySet() {
return keySet;
}
public void setKeySet(char[] keySet) {
this.keySet = keySet;
}
public char[] getAnswerSet() {
return answerSet;
}
public void setAnswerSet(char[] answerSet) {
this.answerSet = answerSet;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSocialNumber() {
return socialNumber;
}
public void setSocialNumber(String socialNumber) {
this.socialNumber = socialNumber;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
The driver class of the project:
public static void main(String[] args) {
SU2018LAB6_DriverCandidate_Wayne Driver = new SU2018LAB6_DriverCandidate_Wayne();
Scanner keyboard = new Scanner(System.in);
int test = 1;
int i;
int score;
while (test == 1) {
System.out.println("Welcome to the Online Driving Test");
System.out.println("To begin, enter your last name");
Driver.setLastName(keyboard.nextLine());
System.out.println("Enter your first name");
Driver.setFirstName(keyboard.nextLine());
System.out.println("Enter your SS number");
Driver.setSocialNumber(keyboard.nextLine());
System.out.println("Enter your phone number");
Driver.setPhone(keyboard.nextLine());
System.out.println("Enter your address");
Driver.setAddress(keyboard.nextLine());
//for (i = 0; i < Driver.getKeySet().length; i++) {
// System.out.println(Driver.getKeySet()[i]);
//}
System.out.println("Driver License Test");
System.out.println("There are 25 multiple choice questions");
System.out.println("You have to get at least 20 questions correct to pass");
System.out.println("---------------------------------");
// This is the area that I am having trouble with
for (i = 0; i < Driver.getKeySet().length; i++) {
System.out.println("Question " + (i + 1) + ": ");
Driver.setAnswerSet(keyboard.next().charAt(0));
}
for (i = 0; i < Driver.getKeySet().length; i++) {
System.out.println(Driver.getAnswerSet()[i]);
}
}
}
The error "The method setAnswerSet(char[]) in the type SU2018LAB6_DriverCandidate_Wayne is not applicable for the arguments (char)" is telling you that the setAnswerSet method is expecting an Array of characters, not a single character. The method let's you overwrite the reference to the array with a new one you pass in.
You have two options: Create an array filled with answers in SU2018LAB6_GradingDLTest_Wayne and "set" it as the new answerSet, or initialize answerSet in SU2018LAB6_DriverCandidate_Wayne and "get" it so you can start filling in the answers.
As it's currently written you can't just get the answerSet and update it because the array hasn't been initialized and is just a null reference.

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

Categories

Resources