How to verify OTP in Java using simple loop? - java

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.

Related

Java - Check online password

This is from Liang's Java Book. Basically, I have to check with a method if a certain word could be used as password.
/*
(Check password) Some websites impose certain rules for passwords. Write a
method that checks whether a string is a valid password. Suppose the password
rules are as follows:
■ A password must have at least eight characters.
■ A password consists of only letters and digits.
■ A password must contain at least two digits.
Write a program that prompts the user to enter a password and displays Valid
Password if the rules are followed or Invalid Password otherwise.
*/
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("This program checks if the password prompted is valid, enter a password:");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
if (isValidPassword(password))
System.out.println("The password is valid.");
else
System.out.println("The password is not valid.");
public static boolean isValidPassword (String password) {
if (password.length() >= 8) {
// if (regex to include only alphanumeric characters?
// if "password" contains at least two digits...
return true;
}
Also, what if (not required) would I to display the exact kind of error? For instance, if I would notify the user that only a kind of error has occurred (e.g. "Your password length is OK, but there are no digits in your password")?
I would do this way:
public class Test {
public static String passwordChecker(String s){
String response = "The password";
int countdigits = 0;
Pattern pattern = Pattern.compile("[0-9]");
Matcher matcher = pattern.matcher(s);
while(matcher.find()){
++countdigits;
}
if(s.length() >= 8){
response = response + ": \n-is too short (min. 8)";
}
else if(!(s.toLowerCase().matches("[a-z]+") && s.matches("[0-9]+"))){
response = response + "\n-is not alphanumeric";
}
else if(countdigits < 2){
response = response + "\n-it doesn't contains at least 2 digits";
}
else{
response = response + " ok";
}
return response;
}
public static void main(String[] args) {
System.out.println("This program checks if the password prompted is valid, enter a password:");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
System.out.println(passwordChecker(password));
}
}
Oops, I forgot to add the rules; well, just use System.out.println :)

How do I return the number of items found after I do a search?

Please help me to figure out how I can get a count of the result when I do a search against a specific folder?
Also how can I ask the user if they want to perform another search?
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
}
}
}
}
If you want to count your matches you can do the following
int i=0;
// Posting the contents
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
i++;
}
}
System.out.println("Total number of results: " + i);`
As for asking the user, consider using a do-while loop in the following format
do{
// your code
// ask user and read his answer on a string called userChoice
}while (userChoice.equals('y'))
Experiment with our suggestions and you will find the answer easily enough!
I would add a variable
int count = 0;
right before the for loop, and just increment it if it's a match.
This should get you started. I am incrementing the variable count each time a match is found. I am also looping forever so it keeps asking the user for more input.
// Importing utilities
import java.io.File;
import java.util.*;
public class FileListing
{
public static void main (String[] args)
{
// Creating a Scanner
Scanner keyboard = new Scanner(System.in);
// Specifying search location
File file = new File("D:/Music");
String[] content = file.list();
while(true){
// Searching for a match
System.out.println("Enter the first few characters of the folder/file to do a lookup");
String userInput = keyboard.nextLine();
// Adding text to say what the user searched for
System.out.println("Below you will find the list of folders/files with a partial match to (" + userInput + ").");
System.out.println();
// Posting the contents
int count=0;
for(String folders : content)
{
if(folders.toUpperCase().startsWith(userInput.toUpperCase()))
{
System.out.println("Name: " + folders);
count++;
}
}
}
}
}
Use a while loop and prompt the user to enter a phrase (such as 'exit') if they want to stop. After reading the user input, check the phrase and call a break if it matches the exit phrase.
Use a variable as Robert suggested to count the total number of files found.

How to make do while loop after validating email address?

// My Scanner
Scanner input = new Scanner(System.in);
//using Do While Loop
do {
//Asking user to enter email
System.out.println("enter your email:");
//Read and safe input in to Var userEmail
String userEmail = input.next();
//Check for contains '#' and '.com' simbols
Pattern pattern = Pattern.compile("\\S+?#\\S+?\\.com");
//And it checking in users entered email
Matcher matcher = pattern.matcher(userEmail);
//if userEmail contain '#'and '.com' print next line
if (matcher.matches()) {
System.out.println("Matches"); // Prints this for this email
}
//if user put email with out '#'and'.com' print next line
else {
System.out.println("your email should
looks like this sample bob.Dillon#gmail.com");
}
// And here I have a problem don't know what to type in
// so that it starts looping until user input will be 100% correct.
} while(!matcher.matches());
Can someone help what needs to be done here while(here); to make it looping?
You want to see if the user entered anything in those fields. So, check like this:
if (INPUTVALUE.length > 0) { //THEY ENTERED SOMETHING
// do something
}
Then, put this in your while statement. Like so:
// My Scanner
Scanner input = new Scanner(System.in);
//using Do While Loop
do{
//Asking user to enter email
System.out.println("enter your email:");
//Read and safe input in to Var userEmail
String userEmail = input.next();
//Check for contains '#' and '.com' simbols
Pattern pattern = Pattern.compile("\\S+?#\\S+?\\.com");
//And it checking in users entered email
Matcher matcher = pattern.matcher(userEmail);
//if userEmail contain '#'and '.com' print next line
if (matcher.matches()) {
System.out.println("Matches"); // Prints this for this email
}
//if user put email with out '#'and'.com' print next line
else{
System.out.println("your email should
looks like this sample bob.Dillon#gmail.com");
}
//And here I have a problem don't know what to type in so that it starts looping until user input will be 100% correct
}while(INPUTVALUE.length > 0);
You need:
}while(INPUTVALUE.length > 0);
To break the loop:
Just erase all of the values that the user has entered at the end of the do. That way, INPUTVALUE.length < 0. That will break the loop ! Good luck !

I need help on the Java Scanner Code

So I need help on this code. This code is all in one so ignore the spaces but I need to write another scanner in the way bottom of the code and if I do add
String feeling = in.nextLine(); at the very end it does not work. I need a it so that I can write my feelings so that I can make jarvis answer but the string does not work and java ignores the string and goes right on to the next part. It starts from the middle.
Scanner in = new Scanner(System.in);
System.out.println("Type User Name:");
String userName = in.nextLine();
System.out.println("PASSWORD:");
int passcodeFromUser=in.nextInt();
int passcode = 2015;
if (passcodeFromUser == passcode) {
System.out.println("Welcome Mr." + userName + "!");
Random random = new Random(userName.hashCode());
System.out.println("Mr." + userName + ", You are now recognized and you are now able to command me.");
System.out.println("I was created by John Choi");
System.out.println("JARVIS stands for Just A Rather Very Intelligent System");
System.out.println("How are you today Mr." + userName + "?");
}
So if I add this code at the back it does not work. It ignores and says Oh. Mr is feeling.
String feeling = in.nextLine();
System.out.println("Oh. Mr." + userName + "is feeling" + feeling + ".")
That is because your nextInt invocation does not actually parse a line feed.
Quoting the API, Scanner#nextInt:
Scans the next token of the input as an int.
(focus on the token part here)
Here's one (but not the only) way to fix it:
Integer passcodeFromUser = null;
try {
passcodeFromUser= Integer.parseInt(in.nextLine());
}
catch (NumberFormatException nfe) {
// TODO handle non-numeric password
}
... instead of int passcodeFromUser=in.nextInt();.
You can also loop the parsing of the Integer so that you print an error message when catching the NumberFormatException and don't break the loop until you have a valid numeric passcode.
You can consume the \n character:
in.nextLine();
String feeling = in.nextLine();
So just putting in.nextLine() before the code you were going to add will easily fix your problem.

Generating username with given information from the user

Hi Im Can Somebody help me with my program ?
my professor ask us to do a program that will get information from the user and generate a 6 letter username from the lastname and firstname of the user.
the first 3 letters of the user name is the first 3 letters of the firstname and the other 3 is the last 3 letters of the lastname of the user. and we need to test it by log-in module
to test if the username and password are match on the generated username and user inputted password
As far as im doing i cant find a answer on this and our professor didn't teach us about this this and im struggling right now.
this is my program right now>>>
public static InputStreamReader r = new InputStreamReader(System.in);
public static BufferedReader i = new BufferedReader(r);
public static void main(String[]args) throws Exception{
String Lname,Fname,Mi;
int age,bday;
float pass;
System.out.print("Enter Last Name: ");
Lname=i.readLine();
System.out.print("Enter First Name: ");
Fname=i.readLine();
System.out.print("Enter Middle Name: ");
Mi=i.readLine();
System.out.print("Age: ");
age=Integer.parseInt(i.readLine());
System.out.print("Birthday (MM/DD/YY) :");
bday=Integer.parseInt(i.readLine());
System.out.println("Password Must Be A 4-6 Digit Combination");
System.out.print("Enter Password : ");
pass=Float.parseFloat(i.readLine());
System.out.println("Please Wait While Generating Your UserName");
for(int j=0;j<=35;j++)
{
try{
Thread.sleep(100);
}
catch(InterruptedException ex)
{
//do nothing
}
System.out.print("*");
}
}
Can Somebody Help Me Please....
You can just:
String username = FName.substring(0,3) + LName.substring(LName.length() - 3, LName.length());
You should probably check that FName and LName have a minimum length of 3 characters, or you will get an exception

Categories