I have a client-server console based application, in client side I have used switch statement for selecting options such as upload/ download/ change password etc. When user enters one number for suppose
String userchoice = console.readLine("Enter your choice :");
int choice= Integer.parseInt(userchoice);
switch (choice){
case 3:
........
Socket soc = new Socket("localhost", 6007);
String reply;
String client = username;
char newpswd[] = console.readPassword("Enter your new Password :");
String newpwd=new String(newpswd);
char newpswd1[] = console.readPassword("Confirm your new Password :");
String newpwd1=new String(newpswd1);
if(newpwd.equals(newpwd1)) {
........
}
else {
S.O.P ("Passwords don't match");
}
break;
After the process has been finished, then I need to send the user to switch (choice) statement again asking for the option number to enter. I have tried continue, return but none worked for me. return - will return to JVM I suppose, which is exiting the program. As goto is not used in Java, what will be my alternative ?
After the process has been finished, then I need to send the user to switch (choice) statement again
Then you need a loop:
while (!quit) {
String userchoice = console.readLine("Enter your choice :");
...
switch (...) {
...
}
}
do {
...
}while(choice != EXIT_CHOICE);
where EXIT_CHOICE is a constant
You can use a while loop, which will execute until it's condition is false or until it is broken from within.
while (some condition) {
String userchoice = console.readLine("Enter your choice :");
......
if (some case is met) {
break;
}
}
It does not work this way. When you get to a switch, it decides (based in the expression evaluated, and the choices present) which will be the next op to be executed, and does nothing more (that is why you need the break statement to avoid running into the next bunch of code).
Get the switch into a loop or a function that gets called twice.
You could put it all in a method that returns a boolean, true if the passwords matched, false if not. Then you could use something like:
boolean loginSuccess = false;
while (!loginSuccess) {
loginSuccess = loginMethod();
}
Edit
Or you could use a do loop...
do {
String userchoice = console.readLine("Enter your choice :");
int choice= Integer.parseInt(userchoice);
switch (choice){
case 3:
........
Socket soc = new Socket("localhost", 6007);
String reply;
String client = username;
char newpswd[] = console.readPassword("Enter your new Password :");
String newpwd=new String(newpswd);
char newpswd1[] = console.readPassword("Confirm your new Password :");
String newpwd1=new String(newpswd1);
} while (!newpwd.equals(newpwd1));
Related
I was trying to build a simple UI where a user enters a username and if the username is xyz then the user will be shown "enter your password". If the password is xyz1234 then the user will be shown "please wait loading..." and the scanner exits. If the username was incorrect, I tried to code it in a way so that it keeps asking for the username until the correct username is entered.
Apparently, the first part of the code works, if the username is xyz, then the code works correctly and displays what i want it to. However if the username is wrong in the first attempt and right in the second attempt, it still continues to show "incorrect username" instead of showing "enter the password".
The code is shown below:
import java.util.Scanner;
class User_Authentication
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter your Username");
String username=in.nextLine();
if(username.equals("xyz"))
{
System.out.println("Enter the Password");
String password=in.nextLine();
if(password.equals("xyz1234"))
{
System.exit(0);
System.out.println("Welcome");
System.out.println("Please wait while the system is loading....");
}
else
{
System.out.println("Your system has been locked for security reasons.");
System.out.println("Please contact an administrator to reset the password");
System.out.println("Any attempt to break in the computer will result in self destruction.");
System.exit(0);
}
}
else
{
do
{
if(username.equals("xyz"))
{
break;
}
System.out.println("Incorrect username");
System.out.println("Please try again");
in.nextLine();
}
while((username.equals("xyz"))==false);
}
}
} ```
Your saying in.nextLine() in your do-while loop, rather than username = in.nextLine()
Replace that and it should work, but overall you're do-while loop needs some work, it's relatively messy. Here's how I would approach it.
do {
System.out.println("Incorrect username");
System.out.println("Please try again");
username = in.nextLine();
} while(username.equals("xyz") == false);
I'm a Java beginner and my project consists of creating a simple program to register users for an alumni center. The process creates an ID and then provides the new user with an OTP. Next is the login (Enter ID:, Enter OTP: ).
My OTP verification method is not working. It seems to be a problem with the IF.equals declaration, the process jumps straight to the ELSE condition.
Any suggestions why?
Here is my code:
class Main {
static NewRegandLogin newRegAndLogin = new NewRegandLogin(null, null, null, null, null, null);
static ArrayList<NewRegandLogin> loginInformation = new ArrayList<>();
public static void main(String[] args) {
System.out.println(" WELCOME TO THE ALUMNI SHE-CODES SYSTEM ");
System.out.println("_________________________________\n - New Alumni registration - \n");
System.out.println("");
newRegAndLogin.registerNewGrad();
System.out.println();
System.out.println("_________________________________");
System.out.println();
System.out.println("Your new Alumni ID is: " + newRegAndLogin.getAlumniId());
System.out.println();
System.out.println("Your temporary password is:");
System.out.println(newRegAndLogin.oTp(8));
loginInformation.add(newRegAndLogin);
System.out.println("_________________________________");
System.out.println("_________________________________\n - Alumni Login - \n");
System.out.println("");
newRegAndLogin.login();
System.out.println("");
System.out.println("Please make a list of completed Courses: -->Enter 'S' to stop adding courses<--");
newRegAndLogin.setAlumniCourses();
System.out.println("_________________________________");
newRegAndLogin.setLinkedInPage();
loginInformation.add(newRegAndLogin);
//printAlumniProfile();
System.out.println("_________________________________");
newRegAndLogin.jobOffer();
}
void login() {
System.out.print("ID: ");
alumniIdImput = scanner.nextLine();
idVerification();
do {
System.out.println("Password (OTP if logging in for the first time): ");
passwordImput = scanner.nextLine();
oTpFromImput = passwordImput.toCharArray();
oTpVerification();
} while (isPasswordCorrect=false);
void oTpVerification() {
isPasswordCorrect = false;
if (oTpFromImput.equals(oTp(8))) {
isPasswordCorrect = true;
System.out.println("Logging In.....");
}else {
isPasswordCorrect = false;
System.out.println("Incorrect password.\nPlease enter valid password: 8 alpha numeric
characters(Aa,123,#,#,$,%)");
}
}
This is the oTp method
char[] oTp (int length) {
String capitalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String smallChars = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String symbols = "!##$%^&*_-=+/.?<>";
String values = capitalChars + smallChars + numbers + symbols;
Random oneTimePassword = new Random();
char[] password = new char[length];
for(int i = 0; i<length;i++) {
password[i] = values.charAt(oneTimePassword.nextInt(values.length()));
}
return password;
}
It seems you built a guessing game, not an OTP verification code.
You first read the OTP from user, and only then randomly generate one to copare to it.
Basically, you code expects the user to guess a random 8 character password that has not been created you, which is basically impossible...
You need to generate to OTP first, show it to the user, then ask them to input it.
I see your logic code is generate OTP code after User input. It seem so wierd bro.
Whenever you call oTp(8) function will generate new OTP.
Use should generate OTP first then store somewhere, then User input and compare it.
You need to store the generated otp somewhere. Then compare it with the input otp. Right now you are comparing it with the otp(8). And otp(8) always returns a new otp.
Hi I'm currently working on an assignment where I have to check if the Resident Password matches with the Door password or not, I have to give the user three tries and after that use assert to show to tell the user to try again. this is my code but the assert is not showing any message.
public static void main(String[] args) throws Exception {
// write your code here
Scanner s = new Scanner(System.in);
String P, pas;
int i = 0;
while (i <= 2) {
System.out.println("Enter Resident Password: ");
pas = s.next();
System.out.println("Enter Door Password: ");
P = s.next();
Resident r = new Resident("XYZ", pas);
Door d = new Door(P);
Dorm D = new Dorm();
D.Check();
if (Resident.getPassword().equals(Door.getPassword())) {
System.exit(0);
} else {
i++;
}
}
assert i>2 : "Serious Error – Program has been terminated Try again later";
}
what should I do to get the message using assert.
From https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html#enable-disable
By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable assertions. To enable assertions at various granularities, use the -enableassertions, or -ea, switch
The way assert works with sending an error message is via using ensuring the condition fails in the case you want. For example:
assert <condition> : <message-if-condition-is-false>;
So if you change your assert to use:
assert i<=2 : "Serious Error – Program has been terminated Try again later";
You throw if i is still <=2. If the condition fails, then the message gets thrown as AssertionError.
So with the above, if I execute it as:
javac Example.java
java -ea Example
and give the desired wrong inputs, you would get:
Exception in thread "main" java.lang.AssertionError: Serious Error, Program has been terminated Try again later
Anyhow, you could choose to use System.err and output the error message:
public static void main(String[] args) throws Exception {
// Write your code here
Scanner s = new Scanner(System.in);
String P, pas;
int i = 0;
while (i <= 2) {
System.out.println("Enter Resident Password: ");
pas = s.next();
System.out.println("Enter Door Password: ");
P = s.next();
Resident r = new Resident("XYZ", pas);
Door d = new Door(P);
Dorm D = new Dorm();
D.Check();
if (Resident.getPassword().equals(Door.getPassword())) {
System.exit(0);
} else {
i++;
}
}
// This need not be verified with if (i>2) because the System.exit(0); will exit if the condition satisfies
System.err.println("Serious Error – Program has been terminated Try again later");
}
I am trying to complete an authentication program for my final project. I am checking for user authentication, if the user info doesn't match the credentials file, the output tells them this and then prompts for username and password while increment an attemptCounter. The only portion I am experiencing an issue with is when I test and incorrect attempt followed by a correct attempt, the while loop will not restart my authentication procedure, instead it simple says incorrect login again. Why isn't my continue statement restarting my while loop iteration?
I tired looking around for this answer on the forum and food nothing specific to my issue. I tried moving my conditional statement as well to see if it was in the wrong spot for my continue to work but it fixed nothing. Compiler says both of my continue statements are unnecessary.
//prompting user for username
System.out.println("Please enter your username (\"L\" to logout \"Q\" to quit): ");
username = scnr.nextLine();
//evaluating if user wants to quit immediately
if(username.equals("Q")) {
System.exit(0);
}
//prompting user for password and storing to password field
System.out.println("Please enter your password: ");
password = scnr.nextLine();
System.out.print("\n");
//while loop that contains the authentication and authorization logic
while (!username.equals("Q") && attemptCounter < 2){
//calling of hashInput method of MD5Hash class to return the hashed user password
userHashedPassword = userHash.hashInput(password);
//while loop to open the credentials for authentication comparison
while (cfScnr.hasNextLine()) {
//assigning the files scanned next line to a field for comparison
line = cfScnr.nextLine();
//conditional statement to determine if username and password are contained on the line
//will break file loop as soon as line contains the user's username and password
//statement logic used to return the role string and remove extra characters and white space
if (line.contains(username) && line.contains(userHashedPassword)) {
dqLocation = line.lastIndexOf('"');
role = line.substring(dqLocation);
role = role.replaceAll("\\s+", "");
role = role.replace("\"", "");
break;
}
}
//conditional statement used to determine if previous loops condtional statement was meant
//if it wasn't this condition will inform the user of incorrect username and/or password
//inform them of attempts remaining and prompt them for a new username and password while
//tracking the attempts and it they want to quit. If Q isn't entered main while loop will restart authentication
if (role == null){
attemptCounter++;
System.out.println("Username or password incorrect. " + (3 - attemptCounter) + " attempts remaining.");
System.out.println("Please enter your username (\"L\" to logout \"Q\" to quit): ");
username = scnr.nextLine();
if(username.equals("Q")) {
System.exit(0);
}
System.out.println("Please enter your password: ");
password = scnr.nextLine();
continue;
}
//this conditional statement runs only when the user is authenticated
else {
//creating new file object and scanner object to scan the role file
File rFile = new File("src\\zooauthenticationsystem\\" + role + ".txt");
Scanner rfScnr = new Scanner(rFile);
//while loop to parse through the role file and output the lines of the file to the console
while (rfScnr.hasNextLine()){
rolePrint = rfScnr.nextLine();
System.out.println(rolePrint);
}
//prompting user if they would like to logout or simply quit the program
System.out.println("\nPress \"L\" to logout and \"Q\" to quit.");
userDecision = scnr.nextLine();
//conditional statement to determine their input, and resetting role to null to reset authentication loop conditional statements, restarts main while loop
if (userDecision.equals("L")){
System.out.println("Please enter your username: ");
username = scnr.nextLine();
if(username.equals("Q")) {
System.exit(0);
}
System.out.println("Please enter your password: ");
password = scnr.nextLine();
System.out.print("\n");
role = null;
continue;
}
Let's get rid of most of your code, let's format the code better, and let's leave only the control structures to see what the continue statements are doing:
while (!username.equals("Q") && attemptCounter < 2) {
userHashedPassword = userHash.hashInput(password);
while (cfScnr.hasNextLine()) {
line = cfScnr.nextLine();
if (line.contains(username) && line.contains(userHashedPassword)) {
// ... do some stuff
break;
}
}
if (role == null) {
// ... do some stuff
continue; // **** (A) ****
} else {
// ... do some stuff
if (userDecision.equals("L")){
// ... do some stuff
continue; // **** (B) ****
}
}
}
If line (A) is reached, you're in the if (roll == null) block, the else will never be entered, and the while loop will repeat regardless of the continue statement making continue unnecessary and distracting.
Likewise if line (B) is reached, you're in the last control block of the while loop, and so the loop will continue regardless of the continue statement making continue unnecessary and distracting.
I am trying to compare the key values of a hashmap with user input but I'm not sure of what approach should be taken.
This is the current code I have:
Scanner scan = new Scanner(System.in);
System.out.println("Type an instruction from the list \n 1. hello \n 2. goodbye");
String input = scan.nextLine();
HashMap helloMap = new HashMap<>();
helloMap.put("hello", "you typed hello");
HashMap goodbyeMap = new HashMap<>();
goodbyeMap.put("goodbe", "you typed goodbye");
if(input.equals(helloMap)){
String helloOutput = (String) helloMap.get("hello");
System.out.println(helloOutput);
}
else if (input.equals(goodbyeMap)){
String goodbyeOutput = (String) goodbyeMap.get("goodbye");
System.out.println(goodbyeOutput);
}
else{
System.out.println("Invalid input");
}
The issue that I've ran into is that when I try to use this program it always defaults to the else clause and this is because I'm used to using .equals to compare it to a String value but I know this is different! Does anyone know the solution for this? Ok so I found a solution for it... It works but is it good enough?
String goodbyeCommand = String.valueOf(goodbyeMap.keySet()).replace("[^a-zA-Z0-9]", "").trim();
String helloCommand = String.valueOf(helloMap.keySet()).replaceAll("[^a-zA-Z0-9]", "").trim();
The problem
You are comparing the input String with the HashMap object. String object is not equal to HashMap object, which is why the boolean expression is always false.
The solution
Please have a look at the following sample:
Map<String, String> outputMap = new HashMap<>();
outputMap.put("hello", "you typed hello");
outputMap.put("goodbye", "you typed goodbye");
System.out.println("Type an instruction from the list \n 1. hello \n 2. goodbye");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
scan.close();
String output = outputMap.get(input);
if (output == null) {
System.out.println("Invalid input");
} else {
System.out.println(output);
}
Breakdown
We define a Map<String, String> containing the program's response mapped to predefined user inputs.
We ask the user for input. When you are done using Scanner, it is good practice to close it by calling .close().
We retrieve the response from the map based on the user input.
We check for null: if it is null, it means the user input was not a valid key for outputMap.
Print the result.
Yes, you need to compare to the actual element of your map instead of the map itself:
Scanner scan = new Scanner(System.in);
System.out.println("Type an instruction from the list \n 1. hello \n 2. goodbye");
String input = scan.nextLine();
HashMap helloMap = new HashMap<>();
helloMap.put("hello", "you typed hello");
HashMap goodbyeMap = new HashMap<>();
goodbyeMap.put("goodbe", "you typed goodbye");
if(input.equals(helloMap.get("hello"))){
String helloOutput = (String) helloMap.get("hello");
System.out.println(helloOutput);
}
else if (input.equals(goodbyeMap.get("goodbe"))){
String goodbyeOutput = (String) goodbyeMap.get("goodbye");
System.out.println(goodbyeOutput);
}
else{
System.out.println("Invalid input");
}