从命令行中输入一个字符串,要求从中随机选择6个字符

从命令行中输入一个字符串,要求从中随机选择6个字符

import java.io.PrintStream;
import java.util.Random;
import java.util.Scanner;

//从命令行中输入一个字符串,要求从中随机选择6个字符
public class RandomDemo {

	public static void main(String args[]){
	
		System.out.print("请输入一行字符串: ");
		Scanner sc = new Scanner(System.in);
		String str = sc.next();
		int sourceLength = str.length();
		int randomLength = 6;
		if(sourceLength <0){
			return;
		}
		
		Random r = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i<6;){
	       int randomNum = r.nextInt(randomLength);
	       if(randomLength >= sourceLength){
	    	  continue; 
	       }
	       i++;
	      // System.out.print(randomNum);
	       sb.append(str.charAt(randomNum));	    
		}
		
		System.out.println(("随机的6个字符为:"+sb));
	}

}
方法二:

避免出现重复的随机数

import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;

public class RandomTest {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("请输入字符串:");
		Scanner scan = new Scanner(System.in);
		String source = scan.next();
		int sourceLength = source.length();
		int randomLength = 6;
		if(sourceLength < 0){
			return;
		}
		Random rand = new Random();
		StringBuilder result = new StringBuilder();
		//存储不重复的随机数
		Set set =new HashSet();
		for(int i=0;i= sourceLength || set.contains(randomNum)){
				System.out.println("set存在随机数:"+randomNum);
				continue;
			}
			i++;
			set.add(randomNum);
			System.out.println(randomNum);
			result.append(source.charAt(randomNum));
		}
		System.out.println("随机的6个字符为:"+result);
	}

	}



版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(从命令行中输入一个字符串,要求从中随机选择6个字符)