如何从名字中随机抽取3个字母,从姓氏和电话号码中随机抽取2个字母,从给定字符串“specialchar”中随机抽取1个符号

yzxexxkh  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(425)
public class testingstring {

   public static void main(String[] args) 
   {
       Scanner userInput = new Scanner (System.in) ;

       String specialChar = "!@#$%^&*()" ;

       System.out.println("Enter your first name: ");
       String firstName = userInput.next() ;

       System.out.println("Enter your last name: ") ;
       String lastName = userInput.next() ;

       System.out.println("Enter your phone number: ") ;
       String phoneNum = userInput.next() ;

   }
}

程序应随机生成8个字符长的密码,如下所示:
名字的3个随机字母
两个随机的姓氏字母
手机号码中的2个随机数字
变量“specialchar”中的1个随机字符

oaxa6hgo

oaxa6hgo1#

1/循环n次int index=(new random()).nextint(specialchar.length());然后将specialchar.charat(索引)放入每个字符串的结果数组中。

j0pj023g

j0pj023g2#

你可以这样做。

import java.util.Scanner;

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

String[] Arr = new String[4];
Scanner S = new Scanner(System.in);
int[] N = new int[4];
char[] Pass = new char[8];

System.out.println("What is your first name?");
Arr[0] = S.nextLine();
System.out.println("What is your last name?");
Arr[1] = S.nextLine();
System.out.println("What is your mobile phone?");
Arr[2] = S.nextLine();
Arr[3] = "!@#$%^&*()";

for (int pos = 0; pos < 4; pos++) {
    N[pos] = Arr[pos].length() - 1;
    switch (pos) {
        case 0:for (int count = 0; count < 3; count++)
            Pass[count] = Arr[0].charAt((int) Math.round(Math.random()*N[0]));
            break;
        case 1:for (int count = 3; count < 5; count++)
            Pass[count] = Arr[1].charAt((int) Math.round(Math.random()*N[1]));
            break;
        case 2:for (int count = 5; count < 7; count++)
            Pass[count] = Arr[2].charAt((int) Math.round(Math.random()*N[2]));
            break;
        case 3:for (int count = 7; count < 8; count++)
            Pass[count] = Arr[3].charAt((int) Math.round(Math.random()*N[3]));
            break;
    }}
System.out.print("Your new password: ");
for (int pos = 0; pos < 8; pos++) {
    System.out.print(Pass[pos]);
}}}
kmbjn2e3

kmbjn2e33#

把问题分解成小块。你的名字叫“帕特里克”。你怎么从字符串“patrick”中随机挑选三个字母?写一小段代码来做这件事,并测试它。然后将它添加到程序的正确位置。
使用类似的逻辑从姓氏和特殊字符字符串中选择。

相关问题