在java中随机使用字符串? [英] Using random with strings in java ?

查看:100
本文介绍了在java中随机使用字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图随机选择4个字符串中的字符串,并在控制台上显示该字符串。我该怎么做 ?例如,有一个问题,如果用户正确回答,那么控制台将显示我选择的一个字符串。我知道如何随机选择一个整数值,但我无法弄清楚如何随机选择一个字符串。请帮忙?

I am trying to choose a string out of 4 strings randomly, and to show this string on the console. How can i do it ? For example, there is a question, if user answers it correctly, then the console will display one of the strings that i chose. I know how to choose an integer value randomly, but i could not figure out how to choose a string randomly. Please Help?

推荐答案

import java.util.Random;
public class RandomSelect {

    public static void main (String [] args) {

         String [] arr = {"A", "B", "C", "D"};
         Random random = new Random();

         // randomly selects an index from the arr
         int select = random.nextInt(arr.length); 

         // prints out the value at the randomly selected index
         System.out.println("Random String selected: " + arr[select]); 
    }
}

使用charAt:

import java.util.Random;
public class RandomSelect {

    public static void main (String [] args) {

         String text = "Hello World";
         Random random = new Random();

         // randomly selects an index from the arr
         int select = random.nextInt(text.length()); 

         // prints out the value at the randomly selected index
         System.out.println("Random char selected: " + text.charAt(select)); 
    }
}

这篇关于在java中随机使用字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆