gpt4 book ai didi

java - 随机替换字符串中随机数的字符

转载 作者:太空宇宙 更新时间:2023-11-04 11:54:18 26 4
gpt4 key购买 nike

我是 Java 新手,我的代码需要一些帮助。

import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;
public class asdf {
public static void main(String[] args)
{
Random generator = new Random();
int num1;
String theWord;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to rearrange");
theWord = in.nextLine();
int length = theWord.length();
Random times=new Random();
System.out.println("Length of String:"+length);
char[] chars=theWord.toCharArray();
Arrays.sort(chars);
int timez=times.nextInt();
num1=generator.nextInt(length);
char c=theWord.charAt(num1);
String newWord=new String(chars);
for(int i=0;i+=1;i<timez)
{
newWord=newWord.replace(c, '*');
}
System.out.println(newWord);
}
}

所以我试图重新排列字符串并用“*”替换一些字符,但它不起作用,我不知道如何修复它。

最佳答案

import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;
public class asdf {
public static void main(String[] args) {
Random generator = new Random();
int num1;
String theWord;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to rearrange");
theWord = in.nextLine();
int length = theWord.length();
Random times=new Random();
System.out.println("Length of String:"+length);
char[] chars=theWord.toCharArray();
Arrays.sort(chars);
int timez=times.nextInt();
num1=generator.nextInt(length);
char c=theWord.charAt(num1);
String newWord=new String(chars);
for(int i=0;i<timez;i++) {
newWord=newWord.replace(c, '*');
}
System.out.println(newWord);
}
}

IDEONE 示例:http://ideone.com/PjfAor

关于java - 随机替换字符串中随机数的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41495113/

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