Any ideas to mask the input? - java

I have been working on small project of mine which has the account name and account password as an array .
After the program runs it ask you to enter your username followed by password then it matches it with its database. If correct: proceed; if not: display login fail.
What I want is when the user enters the password instead of displaying the password as 1234 I want to show it as ****.
{
Scanner in = new Scanner(System.in);
public int UserNameAndPassword(){
System.out.println("Pleass Enter your username:");
String user =in.nextLine();
System.out.println("Pleass Enter your Password:");
String pin = in.nextLine();
int p= FindNameAndPassword(user,pin);
return p;
}
main
public static void main(String[] args) {
HelpingMethodes h =new HelpingMethodes();
Scanner in =new Scanner(System.in);
while(true)
{
int position,choise;
position = h.UserNameAndPassword();
boolean login = true;
while(position==-1)
{
System.out.println("You entered wrong Username or Password");
System.out.print("Pleas try again\n");
position=h.UserNameAndPassword()
}
Is there any simple way to achieve that in Java?

Consider Console.readPassword. Although it will not mask the password with *, it does the job as it hides the text inputted. Quick code snapshot:
char[] password = System.console().readPassword("Password: ");
System.out.println("Password is: "+ password);
Note: You must run the program via command line. If you're running this through an IDE, you will get null on the Console object.
You'll find a detailed tutorial here.
If you prefer not to use Console, you'd have to implement an alternative solution. You'd have to write a thread that overwrites the input as it's received, which won't be a trivial task. As far as I know, Scanner does not have a built-in masking method.

Trying using : http://docs.oracle.com/javase/6/docs/api/java/io/Console.html#readPassword() instead of Scanner.
Also, this is called password masking, not hashing, just FYI.

Related

Java Scanner add optional user input prompts

What is the way to take some parameters as optional user input using java util Scanner? Below is my code. But, for all the parameters it's blocked till the user input is entered.
I want it to continue for second parameter in cases 'when the user input is entered and then pressed enter key' "OR" 'when just pressed enter key without entering any input'.
public class MainApplication {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter ordertypes in comma separated format (mandatory): " );
String orderOrActionTypes = in.next();
System.out.println("Enter orderAttributes (optional): " );
String orderAttributes = in.next();
System.out.println("Enter ActionAttributes (optional): " );
String actionAttributes = in.next();
}
}
You can still let the input but leave it empty.
When an input is required, the user can press Enter (which results on an empty string), and then you can test, whether the user typed something or not orderAttributes.isEmpty() and you do what you need based on the results.
Try using in.nextLine();, it may help.

Incorrect input even though it's a correct input

I'm fairly new to Java and I'm facing some difficulties. So i've been instructed to run a program where you will login in to a system by entering a pin number and school name. You have 3 attempts for each until a message prompts that tells you that the login has failed. My problem is. Everything is fine but in PIN SECTION, (userInputPin==PIN) section, it automatically inputs "Attempt #2 - Enter your school name - Incorrect. upon first correct attempt. When writing the correct school name, it shows login failed as well when it should notify that you have logged in. What's the error?
Note:Ignore comment, I'll fix them.
public class Login {
public static final int PIN = 1234; //Declaring constant for fixed PIN
//Declaring constant for first school name
public static final String FIRST_SCHOOL = "St. Charles";
public static void main(String[] args) {
Scanner kb = new Scanner (System.in); //Declaring scanner object
int attempts = 1; //Declaring variable for attempt number
//Printing first paragraph section of the program
System.out.println("This program simulates logging into a bank account,"
+ "\nasking certain questions for security.\n");
// PIN Section
while(attempts<=3) //While loop
{
System.out.print("Attempt #"+attempts+" - Enter PIN: ");
int userInputPin = kb.nextInt(); //User inputs pin number
//Conditional situations
if(userInputPin==PIN)
{
attempts=1;
while(attempts<=3)
{
System.out.print("\nAttempt #"+ attempts+" - Enter your first school: ");
String userInputSchool = kb.next();
//Conditional situations
if(userInputSchool.equals(FIRST_SCHOOL))
{
System.out.println("\nYou're logged in.");
}
else{
if(attempts==3)
{
System.out.println("\nLogin failed.");
}
else
{
System.out.println("Incorrect.\n");
}
}
attempts++;
}
}
else{
if(attempts==3){
System.out.println("\nLogin failed.");
}
else{
System.out.println("Incorrect.\n");
}
}
attempts++; //Increments attempt by 1 when PIN is incorrect
}
Ah yes, ye ol' Scanner. I can't begin to tell you how many times I've suffered the same problem.
The problem lies in the fact that the nextInt() function sometimes regards the enter key as another token. So when you input the first value, nextInt() recognizes the number inputted. But after printing the second message, the scanner object still has the enter key stored in it. The only way to move forward is to empty the object like so:
if(kb.hasNext()) kb.nextLine();
Insert this after each time you input a number.

How to prevent Java scanner from inputing spaces

I'm trying to prevent the user from inputting spaces or no values.
but nothing works. Even with no entered values program goes further without printing my error. What am I doing wrong?
my code example
Scanner nameScan = new Scanner(System.in);
System.out.print("Input your name: ");
String newcomer = nameScan.nextLine();
player.setName(newcomer);
String userName = player.getName();
userName = userName.trim();
if (userName.length()==0) {
System.out.println(" ");
System.out.println("You have to set up a player name first... ");
System.out.println(" ");
}
else {...
As #11thdimension said, you have to validate the input.
You can do something like:
if (newcomer.isEmpty()) {
System.out.println("Please write something");
}
Or you can do a while loop and keep asking for a correct input.
Your code
if(username.length() == 0)
will not check whether the username contains space because space is counted towards the length of the String.
To check for empty String input(which may contain space(s)), you can do:
if("".equals(username.replaceAll("\\s+",""))) //or
if("".equals(username.trim()) //or
if(username.isEmpty())
Further more, you would want to use a do-while loop for validation instead of using an if-statement.

Java Password Pattern

The password checker program is supposed to take user input of a username and password and output whether the password is valid or invalid.
I've been trying to use regex for this but am having an issue. The pattern works for all my rules but one, the username rule.
Also, is there a way to change the output from "true" or "false" to something custom?
My code so far:
import java.util.regex.*;
import java.util.Scanner;
public class validPassword {
private static Scanner scnr;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Variable Management
String un, pw, req; // Variable Variable
System.out.println("Please enter a username: ");
// ^Need to implement so if it matches the password it's invalid^
un = input.nextLine(); // Gathers user's username input
System.out.println("Please enter a password: ");
pw = input.nextLine(); // Gathers user's password input
req = "(?=.*[0-9])(?=.*[a-zA-Z]).{8,}";
System.out.println(pw.matches(req)); // Can I customize the output?
}
}
I appreciate any help! :)
You should be able to just initially check if it has that sub-sequence.
I would check that initially then check your password rules.
So something like this (using a regex):
// get username and password
if(pw.matches(".*"+Pattern.quote(un)+".*")){
System.out.println("Password can't have username in it...");
}
// make sure password follows rules...
Better would be to use the contains method on strings (docs).
if (pw.contains(un)) {...}
As far as customizing the output of matches you can't. You'll need to conditionally branch and do something different.
For the username check you can change the regex to
"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])((?<!" + Pattern.quote(un) + ").(?!" + Pattern.quote(un) + ")){8,}"
which means at least 8 arbitrary characters that are not followed or preceded by the username. This is with negative lookbehind and negative lookahead just as you used the positive lookahead for the requirement that the three characterclasses are contained.
And regarding the custom output, just use a ternary expression:
System.out.println(pw.matches(req) ? "yehaw" : "buuuuuh")

Why won't my password do-while loop in Java won't Work? What did I do wrong?

I am having a problem with a do-while loop. It has two if statements inside of it. The program is supposed to take your username and password (which you enter) and then confirm them by having you type them in again. When you type them again, the have to be the same as the first time you typed them. The do-while loop is supposed to stop when boolean redo is set to false, (it gets set to false when you re-enter your username and password correctly) however the loop keeps going, even though it says that you got the username and password correct. (It says Welcome, (Username)) then the loop goes again and asks you to re-enter your username and password. How can I stop this loop after getting the correct password? Please help.
package Pack1;
import java.util.Scanner;
public class class1 {
public static void main(String[] args){
String Username; //Used to set the original username
String Password; //Used to set the original password
String Usernameuse; //Used as a test. This one has to be equal to the original username.
String Passworduse; //Used as a test. This one has to be equal to the original password.
boolean redo; //This is to determine whether the do-while loop will repeat.
Scanner in1 = new Scanner(System.in); //getting the original username
System.out.println("Enter your desired username");
Username = in1.nextLine();
Scanner in2 = new Scanner(System.in); //getting original password
System.out.println("Enter your desired password");
Password = in2.nextLine();
System.out.println("Identity Confirmation-- Enter your account information");
do{
Scanner in3 = new Scanner(System.in); //gets second username which has to be equal to original
System.out.println("Please Enter your Username");
Usernameuse = in3.nextLine();
Scanner in4 = new Scanner(System.in); //gets second password which has to be equal to the original
System.out.println("Please Enter your Password");
Passworduse = in4.nextLine();
if(Usernameuse.equals(Username) && Passworduse.equals(Password)){ //determines if both are true
System.out.println("Welcome, " + Username);
redo = false; //makes redo = false
}
if(!Usernameuse.equals(Username) || !Passworduse.equals(Password)){ //determines if either one is false
System.out.println("Either Username or Password are incorrect, please redo");
redo = true; //makes redo = true
}
} while(redo = true); //Is supposed to stop looping when you set redo to false, by entering correct username and password
System.out.println("You are now on your secret account!");
}
}
while(redo = true);
This is an assignment instead of a comparison. This will always be true.
while(redo == true);
is what you meant to type, but
while(redo);
is what you really want because it makes it impossible to commit the assignment-instead-of-comparison error.
When you compare a constant other than a boolean and a variable it's always best to put the constant first for the same reason.
if (1 == someInt)
instead of
if (someInt == 1)
If you accidentally use = instead of == the constant-first form won't compile.
while(redo = true)
Results in always true because it is equal to while(true).
= is assignment
== is comparison.

Categories

Resources