Im having a lot of trouble with randoms in Java and was wondering if someone could help? I am quite new to coding

huangapple go评论71阅读模式
英文:

Im having a lot of trouble with randoms in Java and was wondering if someone could help? I am quite new to coding

问题

将一个随机字符转换为大写,将一个随机字符替换为随机数字,在密码中间添加波浪符~。以下是我在作业中已经完成的部分。

import java.util.Scanner;

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

        String pw;
        int pwl;

        Scanner scan = new Scanner(System.in);

        System.out.println("Enter your word passcode:");
        pw = scan.next();
        pw = (pw.toLowerCase());
        int length = pw.length();
        String firstChar = pw.substring(0, 1);
        String lastChar = pw.substring(length - 1);
        pw = lastChar + pw.substring(1, length - 1) + firstChar;
        System.out.println(pw);

        math.random();

    }
}
英文:

Convert a random character to an upper case,Replace a random character with a random digit,Add a tilde ~ character to the middle of the passcode. Here is what I have got so far in my assignment.

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
 {

String pw;
int pwl;

Scanner scan = new Scanner(System.in);

System.out.println("Enter your word passcode:");
pw = scan.next();
pw = (pw.toLowerCase());
int length = pw.length();
String firstChar = pw.substring(0, 1);
String lastChar = pw.substring(length - 1);
pw = lastChar + pw.substring(1, length-1) + firstChar;
System.out.println(pw);

math.random();

 }
}

答案1

得分: 2

// 将随机字符转换为大写
int random = (int) (Math.random() * pw.length());
pw = pw.substring(0, random) + Character.toUpperCase(pw.charAt(random)) + pw.substring(random + 1);
System.out.println(pw);

// 将随机字符替换为随机数字
random = (int) (Math.random() * pw.length());
pw = pw.substring(0, random) + (int) (Math.random() * 10) + pw.substring(random + 1);
System.out.println(pw);

// 在密码的中间添加波浪符 ~ 字符
int len = pw.length();
pw = pw.substring(0, len / 2) + '~' + pw.substring(len / 2);
System.out.println(pw);
英文:
// Convert a random character to an upper case
int random = (int) (Math.random() * pw.length());
pw = pw.substring(0, random) + Character.toUpperCase(pw.charAt(random)) + pw.substring(random + 1);
System.out.println(pw);

// Replace a random character with a random digit
random = (int) (Math.random() * pw.length());
pw = pw.substring(0, random) + (int) (Math.random() * 10) + pw.substring(random + 1);
System.out.println(pw);

// Add a tilde ~ character to the middle of the passcode.
int len = pw.length();
pw = pw.substring(0, len / 2) + '~' + pw.substring(len / 2);
System.out.println(pw);

huangapple
  • 本文由 发表于 2020年9月29日 02:30:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64107701.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定