gpt4 book ai didi

java - 用其他数组创建一个大数组,IF FALSE 使其更小

转载 作者:行者123 更新时间:2023-12-01 19:48:17 25 4
gpt4 key购买 nike

我一直在开发这个创建密码的程序,它有 4 个字符数组,其中包含可用于密码的所有字符,以及评估用户是否想要使用它们的方法,问题是它只有在所有数组都为“true”(它们被使用)时才有效,因为最后一个数组由 73 个空格组成,这些空格被其他数组填充。问题是,如果用户不想使用其中一个,当 for 循环循环遍历数组时,它大部分会落在一个空的索引号上,破坏代码,我想不出一种方法来解决这个问题

package javaapplication19;

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

public class JavaApplication19 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

char [] leterSmall = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','ñ','o','p','q','r','s','t','u','v','w','x','y','z'};
char[] leterBig = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','Ñ','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char[] numbers = {'0','1','2','3','4','5','6','7','8','9'};
char [] charsRandom = {'?','¿','.',';','+','-','*','/','|'};
char [] arrayFinal = new char[73];

boolean smallOption = false;
boolean bigOption= false;
boolean numbersOption= false;
boolean charactersOption= false;

System.out.println("Do you want to use small leters?");
String answer1 = sc.next();
if( opcionmenu(answer1)==true){
smallOption = true;
for(int i=0;i<27;i++){
arrayFinal[i]=leterSmall[i];
}
}
System.out.println("Do you want to use big leters?");
String answer2 = sc.next();
if( opcionmenu(answer2)==true){
bigOption = true;
for(int i=27;i<54;i++){
arrayFinal[i]=leterBig[i-27];
}
}
System.out.println("Do you want to use numbers?");
String answer3 = sc.next();
if( opcionmenu(answer3)==true){
numbersOption = true;
for(int i=54;i<64;i++){
arrayFinal[i]=numbers[i-54];
}
}
System.out.println("Do you want to use symbols?");
String answer4 = sc.next();
if( opcionmenu(answer4)==true){
charactersOption = true;
for(int i=64;i<73;i++){
arrayFinal[i]=charsRandom[i-64];
}
}

for(int i=0;i<16;i++){
int y = ThreadLocalRandom.current().nextInt(0,73 + 0 );
System.out.print(arrayFinal[y]);

}




}
static boolean opcionmenu(String stra){

if(stra.equals("Yes")) {
return true;
}
else{
return false;
}
}
}

最佳答案

构建 arrayFinal 时,跟踪已添加的值的数量,并且仅在前一个值之后添加一个值。

像这样,其中len是添加到arrayFinal的字符数:

int len = 0;
if (smallOption) {
for (char c : leterSmall) {
arrayFinal[len++] = c;
}
}
if (bigOption) {
for (char c : leterBig) {
arrayFinal[len++] = c;
}
}
if (numbersOption) {
for (char c : numbers) {
arrayFinal[len++] = c;
}
}
if (charactersOption) {
for (char c : charsRandom) {
arrayFinal[len++] = c;
}
}

ThreadLocalRandom rnd = ThreadLocalRandom.current();
for (int i = 0; i < 16; i++) {
System.out.print(arrayFinal[rnd.nextInt(len)]);
}

关于java - 用其他数组创建一个大数组,IF FALSE 使其更小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52396705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com