'How add a data to char array from char variable in Java programming [closed]
I am going to make a password generator. But I cannot a char variable into a char array can you help me? I tried with charAt() but it didn't work well. Now, what should I do?
import java.util.concurrent.ThreadLocalRandom;
public class GenerateRandomString {
/**
* @param args The command-line arguments
*/
public static void RandomMaker(){
String text = "ABCDEFGHIKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
int min_val = 1;
int max_val = 61;
char[] pass = {'1'};
char test = 'x';
ThreadLocalRandom tlr = ThreadLocalRandom.current();
for (int i = 0; i<19; i++){
int randomNum = tlr.nextInt(min_val, max_val);
String x = text.substring(randomNum-1, randomNum);
for(short z = 0; z < 1; z++){
test = x.charAt(0);
}
//char test = x.charAt(0);
//pass[i] = x.charAt(0);
System.out.println(test);
System.err.println(x);
pass[i] = test;
}
System.out.println("\n"+pass.length);
}
public static void main(String[] args) {
// TODO code application logic here
GenerateRandomString obj = new GenerateRandomString();
GenerateRandomString.RandomMaker();
System.out.println("Successful");
}
}
Solution 1:[1]
You are creating a char[] pass variable with size 1. This is why it throws an java.lang.ArrayIndexOutOfBoundsException.
You should initialize with the size you want to use (19). You can try doing:
char[] pass = new char[19];
Another option is define a List and add items dynamically.
I hope this help you.
Solution 2:[2]
If you want to convert text to Character array:
String str = "putyourtexthere";
// Creating array of string length
char[] ch = new char[str.length()];
// Copy character by character into array
for (int i = 0; i < str.length(); i++) {
ch[i] = str.charAt(i);
}
// Printing content of array
for (char c : ch) {
System.out.println(c);
}
Solution 3:[3]
I did it in this way Thanks all (?)
import java.util.*;
public class Random2 {
/**
* @param args the command line arguments
*/
public static String text = "ABCDEFGHIKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*:;,<.>/?'|`";
public static char[] pass = new char[85];
public static int passlength = 0;
public static int x = 0;
public static String y = "1";
public static void generator(){
Random random = new Random();
for (short t= 1; t <= passlength; t++){
x = random.nextInt(text.length());
y = text.substring(x, x+1);
pass[t] = y.charAt(0);
System.out.print(pass[t]);
}
}
public static void main(String[] args) {
// TODO code application logic here
Random2 myclass = new Random2();
Scanner scan = new Scanner(System.in);
passlength = scan.nextInt();
myclass.generator();
//System.out.println(pass.length);
System.out.println("\nSuccesfully");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Progman |
| Solution 2 | meher |
| Solution 3 | Thisaru Samaranayaka |
