功能描述:在控制台上输入一段字符(长度不小于 7,并且不重复的字符长度不小于 7) ,从中随机抽取 7 个字符,要求抽取的字符不能重复,然后将抽取的字符输出。抽取的字符要求用StringBuffer 存储。
运行结果:
我 是 不 是 你 最 疼 爱 的人 你 为 什 么 不 说 话
不 得 人 话 说 人
运行结果:
我 是 不 是 你 最 疼 爱 的人 你 为 什 么 不 说 话
不 得 人 话 说 人
思路就这样。
PS:我个人觉得自己不尝试写写,上来直接要代码是很无耻的行为。
import java.util.Scanner;
import java.util.Random;public class Test{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.print("Input the content:");
String content = keyboard.nextLine();
while(!valid(content)){
System.out.printf("content:'%s' is invalid!\nInput the content again:",content);
content = keyboard.nextLine();
} String result = process(content); Random random = new Random();
int index;
String c;
StringBuffer buffer = new StringBuffer();//用于存储.
for(int i = 0 ; i < VALIDLENGTH ; i ++){
index = random.nextInt(result.length());
c = result.charAt(index) + "";
buffer.append(c);
result = result.replaceAll("[" + c + "]","");
} System.out.println(buffer.toString()); } private static boolean valid(String content){
if(content.length() < VALIDLENGTH){
return false;
}
content = process(content);
if(content.length() < VALIDLENGTH){
return false;
} return true;
} private static String process(String content){
String result = content;
while(!(result = content.replaceAll("(.+)(.*?)\\1","$1$2")).equals(content)){
content = result;
}
return result;
} private final static int VALIDLENGTH = 7;
}
* 功能描述:在控制台上输入一段字符(长度不小于 7,并且不重复的字符长度不小于 7) ,从中随机抽取 7 个字符,
* 要求抽取的字符不能重复,然后将抽取的字符输出。抽取的字符要求用StringBuffer 存储。
* @author student
*
*/
public class GetChar { public static void main(String[] args) {
System.out.println("输入不重复的字符长度不小于 7:");
boolean flag=true;
int index=0;
Scanner sc=new Scanner(System.in);
String str=sc.next();
Random r=new Random();
char[] ch=str.toCharArray();
StringBuffer sb=new StringBuffer();
for (int i = sb.length(); i <7; i++) {
index=r.nextInt(ch.length);
for (int j = 0; j <i; j++) {
if (String.valueOf(ch[index]).equals(sb.substring(j, j + 1))) {
flag = false;
} }
if (flag) {
sb.append(ch[index]);
flag=true;
}
}
System.out.println(sb); }}