How to take an input in asterix WHILE typing? - java

I have to create a login id which takes a password(in java) but I want the input to be in asterix while the user types to make it look professional. Is it even possible? Please give the syntax for the code to be input as asterix.
If the question has been asked before (i could not find it) please link before removing.
Thank You.

If you want to get password from console try the following:
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
char passwordArray[] = console.readPassword("Enter your password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));

Related

Two if statement is executed in java code

Im currently trying to do a validation for staff login form. but i realized in my validation output that whenever i enter a value to the username text field, it still pops up the message "please enter your username" then the "invalid credentials"message box. Here is my code down below :
String username = usernameTxt.getText();
String password = passwordTxt.getText();
if (username.contains(""))
{
JOptionPane.showMessageDialog(null,"Please Enter Your Username Credentials.");
}
else if (password.contains (""))
{
JOptionPane.showMessageDialog(null,"Please Enter Your Password Credentials.");
}
else if (password.contains ("") && (username.contains("")))
{
JOptionPane.showMessageDialog(null,"Please Enter Your Login Credentials.");
}
if ((username.contains("staff") && password.contains ("pass")))
{
JOptionPane.showMessageDialog(null,"Login Successfull","Success",JOptionPane.INFORMATION_MESSAGE);
passwordTxt.setText(null);
usernameTxt.setText(null);
staffdashboard sd = new staffdashboard();
sd.setVisible(true);
this.setVisible(false);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Login Details","Login Error",JOptionPane.ERROR_MESSAGE);
passwordTxt.setText(null);
usernameTxt.setText(null);
}
enter user message box
invalid login details message box
What am i missing out and how do stop the form to output 2 message box at once?
The problem is in the first if statement: username.contains("")
Each String contains empty String.
You should replace it with if("".equals(username))
Or use StringUtils.isBlank(username);
And the same for all the contains("")
#Naya's answer is correct, however you may want to remove any empty spaces assuming they are not allowed as valid input, so :
if (username.trim().equals("")) ...
else if (password.trim.equals("")) ...
...

How to fix while loop error login logout system (no database) (also is there a code about session time)?

I create a basic login and logout system (no database) with the only username given for my school homework, but I have problems with while loops and also session time.
I tried to copy and paste a group of codes to different parts of this main code so that I can get my expected outcome but it turns out to be a bit faulty. I tried to search on the internet about session time but I got nothing.
while (login = true){
try {
System.out.println("Enter your name:");
String name = cue.nextLine();
System.out.println("--------------------");
System.out.println("");
System.out.println("Date and Time of Login:");
System.out.println(dtf.format(now));
System.out.println("");
System.out.println("--------------------");
System.out.println();
System.out.println("Enter your name to log out:");
String logout = cue.nextLine();
System.out.println("");
if (logout.equals(name)){
System.out.println("--------------------");
System.out.println("");
System.out.println("Date and Time of Logout:");
System.out.println(dtf.format(now));
System.out.println("Session Time:");
/*can you also please tell me what code to tell the gap between the
login time and log out time?*/
System.out.println("");
System.out.println("--------------------");
login = false;
} else {
login = true;
}
} catch (Exception e){
cue.nextLine();
} finally{
System.out.println("Do you want to register again? 0 for yes and 1 for no");
int no = cue.nextInt();
if (no==0) {
login = true;
} else if (no==1) {
System.exit(1);
} else {
System.out.println("1 or 0 only!");
}
}
}
This must be the expected output:
if the name is correct:
Enter your name:
nmae
--------------------
Date and Time of login:
2019/02/03 16:38:46
--------------------
Enter your name to log out:
nmae
--------------------
Date and Time of logout:
2019/02/03 16:38:46
Session Time:
(This must show how many minutes and seconds a client uses the program)
--------------------
Do you want to register again? 0 for yes and 1 for no
0
Enter your name:
incorrect and it is corrected later on:
Enter your name:
name
--------------------
Date and Time of login:
2019/02/03 16:38:46
--------------------
Enter your name to log out:
nmae
Enter your name to log out:
name
but it turns out that on second loop, third loop and so on, the program asks me to "enter your name to log out" and "Do you want to register again? 0 for yes and 1 for no" instead. The "enter your name" part prints instead of asking my name.
and then when I enter 0 to exit, this error showed up C:\Users\DELL\AppData\Local\NetBeans\Cache\10.0\executor-snippets\run.xml:111: The following error occurred while executing this line:
C:\Users\DELL\AppData\Local\NetBeans\Cache\10.0\executor-snippets\run.xml:94: Java returned: 1
To get difference beetwen login time and logout time you can use Duration class from java8:
loginTime = LocalDateTime.now();
...
logoutTime = LocalDateTime.now();
Duration.between(loginTime, logoutTime).getSeconds();
You are returning an error level 1, which is the way a program terminates returning an error to the OS.
I can not test is as I do not use Windows, but you could try replacing System.exit(1) with System.exit(0).

making an encryption program and im getting a sytnax error but i dont know why

Currently i'm trying to make a basic program that takes an input of any string such as a sentence or a paragraph and it takes each letter and turns it into a 3 character code once i get this working i'm assuming i should just be able to do the reverse and have it take the 3 digit code and turn it back to text, anyway i'm getting an error when i try to compile the program to test it. i have the issue marked below. also once i get the program working i would like to make a gui for it where you put in the input and it shows the out put after you click a button but as i am just starting out that seems a but advanced for me if you know any good tutorials for it please let me know!
import java.util.Scanner;
import java.util.*;
class test {
private static Scanner inp;
public static void main(String[] args) {
Map <Character, String> encryptionMappings = new HashMap<>();
encryptionMappings.put('a',"{qaz}");
encryptionMappings.put('b',"{wsx}");
encryptionMappings.put('c',"{edc}");
encryptionMappings.put('d',"{rfv}");
encryptionMappings.put('e',"{tgb}");
encryptionMappings.put('f',"{yhn}");
encryptionMappings.put('g',"{ujm}");
encryptionMappings.put('h',"{ik,}");
encryptionMappings.put('i',"{ol>}");
encryptionMappings.put('j',"{p;?}");
encryptionMappings.put('k',"{[']}");
encryptionMappings.put('l',"{qwe}");
encryptionMappings.put('m',"{asd}");
encryptionMappings.put('n',"{zxc}");
encryptionMappings.put('o',"{rty}");
encryptionMappings.put('p',"{fgh}");
encryptionMappings.put('q',"{vbn}");
encryptionMappings.put('r',"{yui}");
encryptionMappings.put('s',"{hjk}");
encryptionMappings.put('t',"{nm,}");
encryptionMappings.put('u',"{iop}");
encryptionMappings.put('v',"{qaw}");
encryptionMappings.put('w',"{sxz}");
encryptionMappings.put('x',"{red}");
encryptionMappings.put('y',"{cvf}");
encryptionMappings.put('z',"{ytg}");
encryptionMappings.put('A',"{hnb}");
encryptionMappings.put('B',"{iuj}");
encryptionMappings.put('C',"{kml}");
encryptionMappings.put('D',"{opl}");
encryptionMappings.put('E',"{wom}");
encryptionMappings.put('F',"{wsv}");
encryptionMappings.put('G',"{ths}");
encryptionMappings.put('H',"{imv}");
encryptionMappings.put('I',"{ybf}");
encryptionMappings.put('J',"{cja}");
encryptionMappings.put('K',"{thw}");
encryptionMappings.put('L',"{maz}");
encryptionMappings.put('M',"{pqa}");
encryptionMappings.put('N',"{zwl}");
encryptionMappings.put('O',"{;ld}");
encryptionMappings.put('P',"{'d;}");
encryptionMappings.put('Q',"{;ny}");
encryptionMappings.put('R',"{;ws}");
encryptionMappings.put('S',"{c/.}");
encryptionMappings.put('T',"{%#^}");
encryptionMappings.put('U',"{/mc}");
encryptionMappings.put('V',"{uka}");
encryptionMappings.put('W',"{zby}");
encryptionMappings.put('X',"{&hd}");
encryptionMappings.put('Y',"{&hw}");
encryptionMappings.put('Z',"{^#^}");
encryptionMappings.put('0',"{$g%}");
encryptionMappings.put('1',"{^#%}");
encryptionMappings.put('2',"{142}");
encryptionMappings.put('3',"{243}");
encryptionMappings.put('4',"{089}");
encryptionMappings.put('5',"{756}");
encryptionMappings.put('6',"{423}");
encryptionMappings.put('7',"{312}");
encryptionMappings.put('8',"{145}");
encryptionMappings.put('9',"{187}");
encryptionMappings.put('~',"{)*(}");
encryptionMappings.put('`',"{$#%}");
encryptionMappings.put('!',"{!^#}");
encryptionMappings.put('#',"{#^&}");
encryptionMappings.put('#',"{^#&}");
encryptionMappings.put('$',"{!?*}");
encryptionMappings.put('%',"{^<+}");
encryptionMappings.put('^',"{+$$}");
encryptionMappings.put('&',"{!!*}");
encryptionMappings.put('*',"{((%}");
encryptionMappings.put('(',"{*&^}");
encryptionMappings.put(')',"{$%^}");
encryptionMappings.put('_',"{&#^}");
encryptionMappings.put('-',"{<>?}");
encryptionMappings.put('=',"{:'^}");
encryptionMappings.put('{',"{%%G}");
encryptionMappings.put('}',"{$$$}");
encryptionMappings.put('[',"{***}");
encryptionMappings.put(']',"{:::}");
encryptionMappings.put(':',"{#$%}");
encryptionMappings.put('|',"{?H*}");
encryptionMappings.put(';',"{B&&}");
encryptionMappings.put('"',"{#gs}");
encryptionMappings.put('?',"{^gl}");
encryptionMappings.put('/',"{#gn}");
encryptionMappings.put('<',"{%TG}");
encryptionMappings.put('>',"{5%5}");
encryptionMappings.put(',',"{yty}");
encryptionMappings.put('.',"{ggg}");
inp = new Scanner(System.in);
System.out.println("Input Password");
int n = inp.nextInt();
if(n!=234) {
System.out.println("Denied Acess");
} else {
System.out.print("Password Accepted"
+ " ");
System.out.print("Input Text to encrypt: ");
String m = inp.next();
String encryptMe = "He";
StringBuilder builder = new StringBuilder();
The below line is the one that shows a syntax error for "toCharArray" i'm not sure why, I just started learning java so if its something simple that i'm missing i'm sorry, any and all help is apreciated.
for (Character c : encryptMe.toCharArray) {
builder.append(encryptionMappings.get(c));
}
String encrypted = builder.toString();
}
}
You are trying to call a method on the object but you are missing the empty () that need to follow toCharArray. Some languages allow you to omit the empty parentheses, but Java is not one of them. You should use:
for (Character c : encryptMe.toCharArray()) {
builder.append(encryptionMappings.get(c));
}
A good IDE (Eclipse, Intellij IDEA, Netbeans, etc.) will help you catch these syntax errors as you learn.

How to deal with Backspace while taking in password in Java?

I need to delete last character entered by user while entering password and I need help in handling Backspace pressed by user.
Below is the code I wrote for Login, how to modify it so that I can handle Backspace ?
void login(){
//As mentioned on internet
Console con=null;
con=System.console();
System.out.println("==============================================================");
System.out.println("\t\t\t LOGIN MENU\n");
System.out.print("\tEnter User Name: ");
String userName=scan.next();
System.out.print("\tEnter Your Password: ");
char[] password = con.readPassword("");
System.out.println(password);
System.out.println("==============================================================");
String pass=new String(password);
//Arrays.fill is used to fill 'spaces' to replace password (Security Concerns)
java.util.Arrays.fill(password, ' ');
//System.out.println(password);
con.flush();
}
Thank You! :)

Java: populating Scanner with default value on Scanner.nextLine();

I am writing a java program that runs a loop and keeps asking the user for input. The program then does a bunch of things with the string, and asks for another string and repeats.
The issue is that many strings are very similar, so i would like to populate the prompt with the input from the last time in the loop. For instance: If the user enters a value as follows:
Enter the SKU Number: APE-6603/A
... Then the next time it asks for an SKU, it will wait till the user presses enter as normal, but be ready with the last value before the user even types anything:
Enter the SKU Number: APE-6603/A
... And the user can make simple changes very fast like replace the /A with /B and press enter! If the string that holds the user input is called "lookFor", is there a way to populate the prompt with this value in Java? It would be VERY useful!
Thanks!
After discussing this idea with a few people, it seems that what i want is not possible. The way of input is too simple to allow something like this.
My only possible solutions involve not running this from my IDE. I can either elect to use my application, or change the application into a GUI based applet. Running from the console will open up the "Press up" option, as suggested by rchirino, and using a GUI would let the value entered sit there for editing later.
If anyone is looking to do what i posted above, the answer is "Java cant do it!". Sorry. :)
You might want to try something like this:
public String promptandgetWithShowDefault(String prompt, String supplied) {
String prmpt = prompt + " (press Enter for \"" + supplied + "\"):";
String tmpch = null;
System.out.print(prmpt);
tmpch = scanner.nextLine().trim();
if (tmpch == null || tmpch.equals("")) {
return supplied;
} else {
return tmpch;
}
}
If the goal is to get a simple binar answer from the user like:
Would you like to do that? ( y / n ) y
then the empty string returned by the user, in the answer from Dmv, will do the trick, except that when the user types "n" or attempts to delete the trailing "y", it won't disappear, so it would then be clearer to write the prompt like:
Would you like to do that? ( [ y ] / n )
But when the goal is to get a long string, like the original question or a file path for instance, that the user can edit to correct a typo or not to overwrite previous file .... then you definitely need something else which doesn't seem to be available in Java.
Well do it in C then!!! with the help of libreadline...
it's probably possible, easier and more portable to do the same trick in Python, but I have no idea how to code in Python.
Here is a simple Java MRE to illustrate it:
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
public class Main
{
public static void main(String[] args)
{
String path = System.getProperty("user.home") + File.separatorChar + "Documents";
File file = null;
do {
path = askForString("Enter the filepath to open:", path );
if ( ( path == null) || ( path.isBlank())) break;
file = new File( path );
} while ( ! file.exists() );
System.out.println("Openning " + path + "....");
// ......
}
public static String askForString( String message, String defaultString)
{
String response = null;
System.out.println( message);
// any extra String in cmd[] will be added in readline history
String[] cmd = { "/path/to/executable/ask4stringWdefault", defaultString};
try
{
ProcessBuilder pb = new ProcessBuilder(cmd);
// Make sure the subprocess can print on console and capture keyboard events
pb.redirectInput(ProcessBuilder.Redirect.INHERIT);
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
Process p = pb.start();
BufferedReader stderrBuffer = new BufferedReader(new InputStreamReader(p.getErrorStream()));
int retcode= p.waitFor();
if ( retcode != 0)
{
System.err.println("The process terminated with error code: " + retcode + "\n" + stderrBuffer.readLine());
return null;
}
response = stderrBuffer.readLine();
} catch( Exception e) {
e.printStackTrace();
}
return response;
}
}
To build the executable "ask4stringWdefault" you need first to get the GNU Readline Library utility and compile it, ideally cross-compile for any platform Java supports, to get a static library that you will link while compiling ( or cross-compiling ) the following C script:
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
#include <readline/history.h>
const char *defstr;
int prefill(const char *txt, int i);
int main(int argc, const char * argv[])
{
if ( argc < 2)
{
fprintf(stderr, "You must provide a default value\n");
return -1;
} else if ( argc > 2) {
// * optional extra values can be passed to populate history * //
if ( argc > 255) argc = 255;
for ( unsigned char i=0; i < argc; i++)
{
add_history(argv[i]);
}
}
defstr = argv[1];
char *cbuffer;
rl_startup_hook = prefill;
if ((cbuffer = readline(NULL)) == NULL) /* if the user sends EOF, readline will return NULL */
return 1;
fprintf( stderr, "%s\n", cbuffer);
free(cbuffer);
return 0;
}
int prefill(const char *t, int i)
{
rl_insert_text(defstr);
return 0;
}
The result is printed on stderr as it is the only stream that Java can keep track of, stdout and stdin being under the control of the executable subprocess itself.
It works fine on a Mac with arm64 architecture, using Eclipse you can't actually edit the default provided, any character typed at the prompt will be append to default string, but just hitting return will send unchanged default value back, which can be enough for basic testing.
I think I understand what you want to do, but it's rather simple. If your program is a console application (command-line), which I'll assume, then you just need to press the UP key to populate the prompt with the last typed characters.
If you're working with GUI elements then you can check the API documentation for the particular class of object you're using and check out it's fields.
Hope this helps!

Categories