Ask coding questions

← Back to all posts
Help With this idea
AaronPhilip (2)

I want to make a One-time Password Generator in java. i have the idea and most of the code i just need help with a few parts of the program.
Anyone with an interest and experience in Java pls hmu in the comments.

Thank you

Answered by PattanAhmed (1103) [earned 5 cycles]
View Answer
Commentshotnewtop
PattanAhmed (1103)

@AaronPhilip Hi,
To make OTP Generator,
Check and try this code:-

import java.util.Random;

public class Tester {
   public static void main(String[] args) {

      System.out.println(generateOTP(4));
   }

   private static char[] generateOTP(int length) {
      String numbers = "1234567890";
      Random random = new Random();
      char[] otp = new char[length];

      for(int i = 0; i< length ; i++) {
         otp[i] = numbers.charAt(random.nextInt(numbers.length()));
      }
      return otp;
   }
}

Output:-

6674

Reference 👆 = Click here

If it didn't work then, Comment me below!
Thanks!

Hope this helps
Please mark my answer if this helps

AaronPhilip (2)

@PattanAhmed Thank you for this answer it really helped a lot. I had completely ignored the fact that we can use character extraction!! Thank you for your time

PattanAhmed (1103)

@AaronPhilip Welcome!
Glad to help
Any more questions are most welcome!

CodeLongAndPros (1369)

@PattanAhmed You know, it’s not really helpful to just give people the solution.

PattanAhmed (1103)

@CodeLongAndPros Hi!
But, I also provided him with the reference link so that he may understand the concepts very well before writing that code
Thanks!

HahaYes (1221)

@PattanAhmed This is blatant spoonfeeding

Vandesm14 (2414)

@HahaYes @CodeLongAndPros Sadly, there's nothing I can do about this, except tell him to not do that.
@PattanAhmed Please don't "spoonfeed" or give direct answers to questions. Always give them a small bit of example code so they can learn how things work rather than copy+pasting it into their repls.

Vandesm14 (2414)

@Vandesm14 Taking a better look, it's not that bad. But my point still stands.

PattanAhmed (1103)

@Vandesm14 I will be more careful next time!
Thanks for your advice!

SixBeeps (3064)

Sounds simple enough, but may I recommend using a single string to store the characters instead?

AaronPhilip (2)

@SixBeeps
That is a very good idea! But my issue is that i cannot hod the randomly generated String in a Variable. Let me add my Repl and please go through it when you have the time.

SixBeeps (3064)

@AaronPhilip You can, say the alphanum variable is declared as such:

static String alphanum = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";

You can get the N'th character by saying:

alphanum.charAt(N);

Also, I see that you aren't really storing the final string in the store variable, I'd recommend appending the new random letter to it:

store += alphanum[rand.nextInt(36)]; // Works with the current setup