[java] How to code a very simple login system with java

I need to create a system that checks a file for the username and password and if it is correct, it says whether or not in a label. So far I have been able to simply make one username and password equal to the variable, but need to link it to a file somehow. I am a noob programmer so lots of help is appreciated. Here is what I have under my authenticate button.

String pass;
String user;
user = txtUser.getText();
pass = txtPass.getText();

if(pass.equals("blue") && user.equals("bob") ){
    lblDisplay.setText("Credentials Accepted.");
}
else{
    lblDisplay.setText("Please try again.");
}     

This question is related to java login passwords system

The answer is


Check this code :

import java.util.Scanner;

public class Main {

public static void main(String[] args) throws IllegalAccessException {

    String username ;
    String password;
    String yes_0r_no;
    String scann;
    String passscan;

    Scanner scan = new Scanner(System.in);
    Scanner scanner = new Scanner(System.in);

    Scanner name = new Scanner(System.in);
    System.out.println("Username:");
    username = name.next().toLowerCase();

    Scanner pass = new Scanner(System.in);
    System.out.println("Password:");
    password = pass.next().toLowerCase();


    System.out.println("You are logged in");

    Scanner ask = new Scanner(System.in);
    System.out.println("Do you want to check this or not(yes or no) :");

     yes_0r_no = ask.next().toLowerCase();



    while (true){
        if (yes_0r_no.equals("yes")){
            System.out.println("Username:");
          scann = scan.next().toLowerCase();
          if (scann == username) {
              continue;
          }
        System.out.println("Password");
        passscan = scanner.next().toLowerCase();
        if (passscan.equals(password)) {
            System.out.println("You are logged in");
            break;

        }if (!password.equals(passscan)) {
            throw new IllegalAccessException();
            }
        }

        if (yes_0r_no.equals("no"))
            break ;



    }


}

}


Map<String, String> d = new HashMap<>();

void input(String u, String p, String e) {
    read();
    if (e.equals("login")) login(u, p);
    else if (e.equals("register")) register(u, p);
    write();
}

void read() {
    d = new HashMap<>();
    String s = "";
    try {
        s = new String(Files.readAllBytes(Paths.get("data.txt")));
    }catch(IOException e) {
        e.printStackTrace();
    }
    String [] pairs = s.split("\n");
    for (int i = 0; i < pairs.length; i++) {
        d.put(pairs[i].split(",")[0], pairs[i].split(",")[1]);
    }
}

void write() {
    try (FileWriter m = new FileWriter("data.txt")) {
        for (Map.Entry<String, String> entry : d.entrySet()) {
            m.write(entry.getKey() + "," + entry.getValue() + "\n");    
        }
        m.close();
    }catch (IOException e) {
        e.printStackTrace();
    }
}

boolean login(String u, String p) {
    return (d.get(u).equals(p)) ? true : false;
}

boolean register(String u, String p) {
    if (d.containsKey(u)) return false;
    d.put(u, p);
    return true;
}

this is my first code on this site try this

import java.util.Scanner;
public class BATM {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    String username;
    String password;

    System.out.println("Log in:");
    System.out.println("username: ");
    username = input.next();

    System.out.println("password: ");
    password = input.next();

    //users check = new users(username, password);

    if(username.equals(username) && password.equals(password)) 
        System.out.println("You are logged in");



}

}

import java.<span class="q39pbqr9" id="q39pbqr9_9">net</span>.*;
import java.io.*;

<span class="q39pbqr9" id="q39pbqr9_1">public class</span> A
{
    static String user = "user";
    static String pass = "pass";
    static String param_user = "username";
    static String param_pass = "password";
    static String content = "";
    static String action = "action_url";
    static String urlName = "url_name";
    public static void main(String[] args)
    {
        try
        {
            user = URLEncoder.encode(user, "UTF-8");
            pass = URLEncoder.encode(pass, "UTF-8");
            content = "action=" + action +"&amp;" + param_user +"=" + user + "&amp;" + param_pass + "=" + pass;
            URL url = new URL(urlName);
            HttpURLConnection urlConnection = (HttpURLConnection)(url.openConnection());
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setRequestMethod("POST");
            DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
            dataOutputStream.writeBytes(content);
            dataOutputStream.flush();
            dataOutputStream.close();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String responeLine;
            StringBuilder response = new StringBuilder();
            while ((responeLine = bufferedReader.readLine()) != null)
            {
                response.append(responeLine);
            }
            System.out.println(response);
        }catch(Exception ex){ex.printStackTrace();}
    }

Code

import java.util.Scanner;

public class LoginMain {

public static void main(String[] args) {

    String Username;
    String Password;

    Password = "123";
    Username = "wisdom";

    Scanner input1 = new Scanner(System.in);
    System.out.println("Enter Username : ");
    String username = input1.next();

    Scanner input2 = new Scanner(System.in);
    System.out.println("Enter Password : ");
    String password = input2.next();

    if (username.equals(Username) && password.equals(Password)) {

        System.out.println("Access Granted! Welcome!");
    }

    else if (username.equals(Username)) {
        System.out.println("Invalid Password!");
    } else if (password.equals(Password)) {
        System.out.println("Invalid Username!");
    } else {
        System.out.println("Invalid Username & Password!");
    }

}

}

One way you could do it is have a file with the username and pass directly under it. Then uses the Scanner class and when you create it, make the file the parameter for the Scanner. Then use the methods hasNext(); and nextLine to verify the username and password;

String user;
String pass;

Scanner scan = new Scanner(new File("File.txt"));

while(scan.hasNext){ //While the file still has more lines remaining
     if(scan.nextLine() == user){
          if(scan.nextLine == pass){
                   lblDisplay.setText("Credentials Accepted.");
          }
          else{
               lblDisplay.setText("Please try again.");
          }
     }
}

import java.util.Scanner;

public class LoginMain {

public static void main(String[] args) {

    String Username;
    String Password;

    Password = "123";
    Username = "wisdom";

    Scanner input1 = new Scanner(System.in);
    System.out.println("Enter Username : ");
    String username = input1.next();

    Scanner input2 = new Scanner(System.in);
    System.out.println("Enter Password : ");
    String password = input2.next();

    if (username.equals(Username) && password.equals(Password)) {

        System.out.println("Access Granted! Welcome!");
    }

    else if (username.equals(Username)) {
        System.out.println("Invalid Password!");
    } else if (password.equals(Password)) {
        System.out.println("Invalid Username!");
    } else {
        System.out.println("Invalid Username & Password!");
    }


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to login

How to center a component in Material-UI and make it responsive? SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost' Angular redirect to login page Swift add icon/image in UITextField SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)" vagrant login as root by default Node.js https pem error: routines:PEM_read_bio:no start line EditText underline below text property Given URL is not allowed by the Application configuration Facebook application error how to get login option for phpmyadmin in xampp

Examples related to passwords

Your password does not satisfy the current policy requirements Laravel Password & Password_Confirmation Validation Default password of mysql in ubuntu server 16.04 mcrypt is deprecated, what is the alternative? What is the default root pasword for MySQL 5.7 MySQL user DB does not have password columns - Installing MySQL on OSX Changing an AIX password via script? Hide password with "•••••••" in a textField How to create a laravel hashed password Enter export password to generate a P12 certificate

Examples related to system

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)' How to code a very simple login system with java Convert R vector to string vector of 1 element How to run cron once, daily at 10pm Java system properties and environment variables A terminal command for a rooted Android to remount /System as read/write Difference between subprocess.Popen and os.system How can I store the result of a system command in a Perl variable? Adding system header search path to Xcode How can I check the system version of Android?