在字符串中选取一个随机字母

时间:2015-12-17 01:53:52

标签: java string random input

我正在尝试从用户输入的字符串中随机选择三个字母,到目前为止我有这个:

    Scanner reader = new Scanner(System.in)
    String inp = reader.nextLine();
            String inputName1;
            inputName1 = inp.substring(int i = (int)(Math.random()*(inp.length()-0)+0), i+=1);

我觉得我错过了一些显而易见的东西,我对Java很陌生,但是有人可以帮助我吗?谢谢大家

5 个答案:

答案 0 :(得分:2)

你想要的是一种名为Knuth shuffle(又名Fisher-Yates shuffle)的东西。 这种算法允许您随机选择向量的元素(此处为您的字符串),而无需替换。要获得这样的结果,您只需要对矢量(或字符串)进行排序,然后选择第一个 n 元素来获取 n 随机选取的元素而不重复。< / p>

“Fisher-Yates洗牌类似于从帽子中随机挑选编号的票(组合:可辨别的物品),而没有替换,直到没有剩下。”在Knuth Shuffle wikipedia article

Java Knuth shuffle代码示例:

public class Knuth { 

// this class should not be instantiated
private Knuth() { }

/**
 * Rearranges an array of objects in uniformly random order
 * (under the assumption that <tt>Math.random()</tt> generates independent
 * and uniformly distributed numbers between 0 and 1).
 * @param a the array to be shuffled
 */
public static void shuffle(Object[] a) {
    int N = a.length;
    for (int i = 0; i < N; i++) {
        // choose index uniformly in [i, N-1]
        int r = i + (int) (Math.random() * (N - i));
        Object swap = a[r];
        a[r] = a[i];
        a[i] = swap;
    }
}

/**
 * Reads in a sequence of strings from standard input, shuffles
 * them, and prints out the results.
 */
public static void main(String[] args) {

    // read in the data
    String[] a = StdIn.readAllStrings();

    // shuffle the array
    Knuth.shuffle(a);

    // print results.
    for (int i = 0; i < a.length; i++)
        StdOut.println(a[i]);
}

}

Java Knuth shuffle example

中的

答案 1 :(得分:1)

您可以计算3个数字,然后通过charAt()获得3个随机字符,然后将它们连接成一个字符串。
你可以实现这样的东西:

Scanner keyboard = new Scanner(System.in);
String inp = keyboard.nextLine();
Random generator = new Random();
String newString = ""; //contains the extracted letters
int randomPositionOfLetter; 
for(int i=1;i<=3;i++){
    // calculating a random position of a char in the string
    randomPositionOfLetter = generator.nextInt(inp.length());
    newString = newString + inp.charAt(randomPositionOfLetter);
}

您还可以修改代码,使其无法多次随机选择相同的数字。

答案 2 :(得分:1)

首先,请改用java.util.ThreadLocalRandom。请参阅this了解原因。您可以做的是使用ThreadLocalRandom选择字符串的随机索引,并使用charAt()方法获取索引中的字符。

    Scanner reader = new Scanner(System.in);
    String inp = reader.nextLine();
    char[] chars = new char[3];

    for(int x = 0; x < 3; x++){
        chars[x] = inp.charAt(ThreadLocalRandom.current().nextInt(0, inp.length()));  
    }

    System.out.println(Arrays.toString(chars));

答案 3 :(得分:0)

您可以计算3个随机数,然后选择将这些数字作为字符串中的位置的字符。使用方法Random.nextInt()比使用Math.random()更好。您可以查看this post了解更多详情

import java.util.Scanner;

public class Test {

    public static void main( String args[] ){
        Scanner reader = new Scanner(System.in);
        String inp = reader.nextLine();
        java.util.Random rnd = new java.util.Random();
        int i = rnd.nextInt(inp.length()), 
                j = rnd.nextInt(inp.length()), 
                k = rnd.nextInt(inp.length());

        System.out.println("Letter 1: "+inp.charAt(i)+", Letter 2: "+inp.charAt(j)+" and Letter 3: "+inp.charAt(k));
    } 

}

答案 4 :(得分:0)

我认为只是简单地做:获取用户输入,从该String生成随机数。重复该步骤,直到达到随机长度(此处为3个字符)。然后打印结果。您还可以允许用户输入更多输入或停止输入。像下面的代码一样:

   public class GenerateString {

    public static void main(String[] args) {        
        generateChars(3);
    }
    /**
     * get input from user at start
     * */
    public static String getInputString(int length) {
        System.out.println("Put your String to get " +  length + " random chars: ");
        Scanner input = new Scanner(System.in);
        String userInput = input.nextLine();

        if(userInput.length() < length) {
            System.out.println("Your input is less than " + length + ".");
            userInput = getInputString(length);
        }

        return userInput;
    }

    /**
     * generate chars with the given length
     * */
    public static void generateChars(int length) {

        String input = getInputString(length);
        int i = 0;
        int inputLength = input.length();
        StringBuilder stringBuilder = new StringBuilder();
        while(i < length) {
            char randomChar = input.charAt(getRandomPosition(inputLength));
            stringBuilder.append(randomChar);
            i++;
        }
        System.out.println("Your random string is: " + stringBuilder.toString());
        stop(length);
    }

    /**
     * get random position
     * */
    public static int getRandomPosition(int length) {
        Random generator = new Random();
        return generator.nextInt(length);
    }

    /**
     * stop the program
     * */
    public static void stop(int length) {
        System.out.println("Do you want to stop? Press 2 to continue, press any number to exit.");
        Scanner input = new Scanner(System.in);
        try {
            int in = input.nextInt();
            if(in == 2) {
                generateChars(length);
            } else {
                System.exit(1);
            }   
        } catch(Exception ex){
            System.out.println("Input is not number!");
            stop(length);
        }

    }
}

@Fool:你能试试吗?!希望这有帮助!