This question already has an answer here:
word (password) displays in asterisks - Console application
(1 answer)
Closed 9 years ago.
my password program can hide keyboard input . its invisible when i type password.
But my qus is how can show password input as asterisk (*)
can any one help me please? :p
my code is here:
public void login()
{
Scanner input = new Scanner(System.in);//create Scanner object
System.out.println("\n");
Console console = System.console();
char[] ad_password = "admin".toCharArray();
char[] sm_password = "salesman".toCharArray();
char[] passwordEntered = console.readPassword("Enter Password To Access The Project ( As Admin / Sales Man ): ");
if (Arrays.equals(ad_password, passwordEntered))
{
System.out.println("\n Congratulation!!! Access granted \n");
System.out.println("\n Welcome Admin. :-) \n\n");
Shoping_mall obj_ad_dis=new Shoping_mall();
obj_ad_dis.ad_dis();
}
else if(Arrays.equals(sm_password, passwordEntered))
{
System.out.println("\n Congratulation!!! Access granted \n");
System.out.println("\n Welcome Sales Man. :-) \n\n");
Shoping_mall obj1_sm_dis=new Shoping_mall();
obj1_sm_dis.sm_dis();
}
else
{
System.out.println("\n Error: Your Password Doesn't Meet. Access Denied !!! :-( \n\n");
System.out.println("\n Enter Correct Password.\n\n");
Shoping_mall obj_login=new Shoping_mall();//creat object for calling Admin_works() method
obj_login.login();
}
}
You can use JPasswordField to do that; Below is an example:
private JPasswordField password;
private String typedPassword;
private final String defaultPassword = "yourDesiredPassword";
public void createPasswordField(){
password = new JPasswordField(30);
password.setBounds(280, 240, 90, 20);
password.setEchoChar('*');
password.setBackground(Color.white);
password.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
password = (JPasswordField) e.getSource();
char [] tempPass = password.getPassword();
typedPassword = new String(tempPass);
if (!typedPassword.equals(defaultPassword)){
JOptionPane.showMessageDialog(null,
"Your password is not correct",
"Stack Over Flow example",
JOptionPane.ERROR_MESSAGE);
}
}
});
}
Related
I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('') to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer + "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText is completely clear?
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
The variable userAnswer doesn't get cleared when answerText is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer); is called at a point where userAnswer is empty (because it can't make a number out of nothing).
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I am doing a project for school, and I am trying to make it to where you can set up a name for yourself while going through a series of questions asked by the computer. I want the user to be able to change their name right after assigning it if they do not like what they put down or they typed something wrong.
Right now the program assigns the name the user wants correctly the first time, but when it goes back through the loop to change it to something else the string is left blank.
Console Output
'''
import java.util.*;
public class JavaInputProdject
{
public static void main(String args[])
{
int i=0;
boolean boo = false;
int likeab = 0;
byte age;
boolean Old=false;
boolean aAge=true;
String user="User";
String un = user + "> ";
Scanner bob = new Scanner(System.in);
System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n"+un);
do
{
user = bob.nextLine();
System.out.println("Bob> This is the Username you want? \""+ user +"\"(true/false)");
System.out.print(un);
if(bob.nextBoolean()==true)
{
boo = true;
un = user + "> ";
}
else
{
if(i>=3)
{
System.out.println("Bob> I realize it is kind of hard to pick a name but could you hurry up?");
}
System.out.print("Bob> Please type in a new Username\n"+un);
bob.next();
i++;
}
} while(boo==false);
}
}
'''
You need to replace the line bob.next() (near the end of the do-while loop) with bob.nextLine().
I believe that bob.next() does not consume the newline that is entered as a result of hitting the <ENTER> key after the bob.nextBoolean() call. Hence the user = bob.nextLine(); line (at the start of the do-while loop) is consuming that newline on the second and subsequent loop iterations. So replacing bob.next() with bob.nextLine() will resolve the problem.
For the sake of completeness, here is the corrected code:
import java.util.Scanner;
public class JavaInputProdject {
public static void main(String[] args) {
int i = 0;
boolean boo = false;
int likeab = 0;
byte age;
boolean Old = false;
boolean aAge = true;
String user = "User";
String un = user + "> ";
Scanner bob = new Scanner(System.in);
System.out.print("Bob> Hey User, My name is BOB.... what is your name?\n" + un);
do {
user = bob.nextLine();
System.out.println("Bob> This is the Username you want? \"" + user + "\"(true/false)");
System.out.print(un);
if (bob.nextBoolean()) {
boo = true;
un = user + "> ";
}
else {
if (i >= 3) {
System.out.println(
"Bob> I realize it is kind of hard to pick a name but could you hurry up?");
}
System.out.print("Bob> Please type in a new Username\n" + un);
bob.nextLine();
i++;
}
} while (boo == false);
}
}
Refer to Scanner is skipping nextLine() after using next() or nextFoo()?
when you want to get correct username based on false flag you doesnt init a value to user.
you should write something like this with bob.nextLine :
System.out.print("Bob> Please type in a new Username\n"+un);
user = bob.nextLine();
i++;
I have a task to do which involves asking the user to input their last name and giving the user an account number to login to the program. I have listed the steps below which might make more sense.
1) User creates an account
2) User enters their last name (Stores into the arraylist)
3) User is given an account number (Stores into the arraylist)
4) User can then login using their last name and account number (checks arraylist for lastname and accountnumber, if it matches then login message, if it doesnt then error message)
A user enters their last name and they are given an account number which they then use to login to deposit, withdraw and check balance.
How do i create a programe to do this without the use of database?
Account Class
private static int number = 500;
Account(){
accountNumber = number++;
}
Create Account
public void createAccount(){
String firstName;
System.out.print("Please Enter Last Name: ");
lastName = scanner.nextLine();
System.out.println("This is your Account Number to log into: " + _______ );
}
public void logIn(){
System.out.println("Please enter your last name: ");
System.out.println("Please enter your account number: ");
}
I would like to suggest another method using xml to store credentials follow the steps below
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string username;
string pwd;
string CurrentUser = "";
string CurrentPwd = "";
bool LoginStatus = false;
username = Login1.UserName;
pwd = Login1.Password;
XmlDocument xmxdoc = new XmlDocument();
xmxdoc.Load(Server.MapPath("Register.xml"));
XmlNodeList xmlnodelist = xmxdoc.GetElementsByTagName("user");
foreach (XmlNode xn in xmlnodelist)
{
XmlNodeList xmlnl = xn.ChildNodes;
foreach (XmlNode xmln in xmlnl)
{
if (xmln.Name == "Name")
{
if (xmln.InnerText == username)
{
CurrentUser = username;
}
}
if (xmln.Name == "Password")
{
if (xmln.InnerText == pwd)
{
CurrentPwd = pwd;
}
}
}
if ((CurrentUser != "") & (CurrentPwd != ""))
{
LoginStatus = true;
}
}
if (LoginStatus == true)
{
Session["UserAuthentication"] = username;
Session.Timeout = 1;
Response.Redirect("welcome.aspx");
}
else
{
Session["UserAuthentication"] = "";
}
}
in your xml file
<user>
<Name>smashcode</Name>
<Password>smashcode</Password>
</user>
I guess this would be better approach than a arraylist approach
if you want to try in using arraylist follow steps
step1:username_list{uesr1,user2,user3}
password_List{pass1,pass2,pass3}
step:check all entries with entered userid and password in a loop as follows
int flag = 0;
while(username_list.get(i)!=null)
{
if((username_list.get(i).equals(enteredusername))&&((password_list.get(i).equals(enteredpassword)))
{
flag = 1;
}
}
if(flag==1)
{
System.out.println("login successful ");
Response.Redirect("welcome.aspx");
}
I had written second code implementation in cut short
Hope my work will be helpful.Keep coding
Not a full answer here but a few suggestions....
You could create a "bank" class... It might hold the arraylist of accounts, also holding
createAccount()
delAccount()
findAccount()...
So on and so forth
Having posted this I now see it is an answer, my bad guys
I assume you need to be able to keep this information after the execution is complete, which means you need to store the information somewhere besides the running program.
Of the top of my head, you can use a file to store this store of information, where each line of the file would equal a match of last name - account. When opening the program, you read the file. Try reading:
http://www.tutorialspoint.com/java/java_files_io.htm or
https://docs.oracle.com/javase/tutorial/essential/io/file.html
The solution is similar to using a database, so I don't know if it will do or not. Hope it does.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
So I am asking the user for their username, and if the user types in "username" then he/she will have "Correct, that is your username!" displayed and if they get it wrong they will get "Incorrect, that is not your username!" displayed.
The problem I am having is that whenever I type the username, in this example the username being "username" I have the Incorrect message displayed.
I would like to know where I went wrong and if this question has been asked a million times if someone could direct me to one of those posts where this has been solved that would be great since I can't seem to find one that's like this problem.
import javax.swing.*;
import java.util.Scanner;
public class userID {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String username;
String password;
String email;
String scanner1;
username = "username";
password = "password";
email = "emailhere";
System.out.println("------------------------------------------");
System.out.println("Welcome to the ID memory tester");
System.out.println("Author: me");
System.out.println("------------------------------------------");
System.out.println("What is your username?");
scanner1 = (input.nextLine());
if (scanner1 == username) {
System.out.println("Correct, that is your username!");
} else {
System.out.println("Incorrect, that is not your username!");
}
}
}
== operator compares references.
You need to use .equals().
Change it to
if (scanner1.equals(username)) {
System.out.println("Correct, that is your username!");
} else {
System.out.println("Incorrect, that is not your username!");
}
I have a version of a login for an employee system i would like to make, I have a for loop which should go through the entire list of Accounts, then see if the name of an employee matches one in the list then the if statement continues, further questions asked etc... it seems to only iterate once and then stop as it will only find the first user and tell me the other accounts do not exisit, even though they do!! What am i doing wrong? Also my list contains Employees and Managers which inherit from Account, the if statement uses the getName in Account to compare if it equals to the user input. Sorry if this is ridiculously stupid/bad! thanks.
List <Account> Accounts = new LinkedList<Account>();
Here is where i populate my Account, the main method calls this and the list() is called whihc contains the problematic loop
public void add() {
Employee Geoff = new Employee("Geoff", "password1");
Manager Bob = new Manager("Bob", "password2");
Employee John = new Employee("John", "password3");
Accounts.add(Geoff);
Accounts.add(Bob);
Accounts.add(John);
list();
}
problem:
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
}
}
System.out.println("Employee does not exist!");
login();
}
I am doing the print statement in the for loop to see what it is findng, and unfortunalty it is only the first account
EDIT: I have included more code here, my after my initial if statement i want to check if the code the user enters is also correct.
see if the name of an employee matches one in the list then the if
statement continues, further questions asked etc... it seems to only
iterate once and then stop as it will only find the first user and
tell me the other accounts do not exisit, even though they do!!
If it works for one employee and tells that others don't exist then your for loop does not iterate once.
The output you get is exactly what the code looks like. You get username once then try to match the same name with every employee in the list. If the names are equal you ask for password, otherwise you print out that employee doesn't exist. Everything right as it is in the code. You should add to your question the expected behaviour so I, or someone else can fix your code without guessing the purpose of your methods.
Here's one of those guesses:
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
boolean userFound = false;
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
userFound = true;
break;
}
}
}
if(userFound) {
login();
} else {
System.out.println("User not found.");
}
This is a possible solution that doesn't use your Account class (since I do not know what it looks like) and instead uses a Map:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = input.nextLine();
boolean found = false;
Map<String, String> accounts = new HashMap<String, String>();
accounts.put("Geoff", "password1");
accounts.put("Bob", "password2");
accounts.put("John", "password3");
Set<String> names = accounts.keySet();
for (String a : names)
{
if (!a.equals(empName))
{
continue;
}
found = true;
// three tries to login
boolean success = false;
for(int i = 0; i < 3; i++)
{
System.out.println("Please enter your passcode: ");
String code = input.nextLine();
if (accounts.get(a).equals(code))
{
System.out.println("logged in");
success = true;
}
else
{
System.out.println("Wrong password... try again");
}
}
if(!success)
{
System.out.println("User failed to authenticate after 3 attempts. User has been locked out!");
}
}
if(!found)
{
System.out.println("Employee does not exist!");
}
}
Since I do not know what the login() method does, I just simply added that into the code. This solution iterates three times in an attempt to get the correct password. If that fails, a message is displayed.