如何从给定的列表中随机生成? [英] How To Randomly Generate From A Given List?

查看:23
本文介绍了如何从给定的列表中随机生成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题是从特定列表中随机生成名称.我希望我的程序只能从以下名称中进行选择:Bob、Jill、TomBrandon.我尝试研究数组,但我认为这对我来说有点太远了.到目前为止,我想我有一个大致的想法,但我不确定.

The problem I'm running into is to randomly generate names from a specific list. I want my program to be able to only pick from these names: Bob, Jill, Tom, and Brandon. I tried studying arrays but I think that's a bit too far for me to learn yet. So far I think I have a general idea, but I'm not sure.

import java.util.Random;

public class NameGenerator
{

        public static void main(String[] args)
        {

           System.out.println("This is a program that generates random names from a list!");

           int Bob = 0;
           int Jill = 0;
           int Tom = 0;
           int Brandon = 0;
           Random r = new Random();

在那之后,我有点纠结于如何让发电机运转起来.

After that I'm kind of stuck on how to get the generator going.

更新:好吧,我接受了您的建议并尝试学习数组.到目前为止,这就是我所拥有的.

Update: Well I took your advices and tried learning arrays. So far this is what I have.

ArrayList<String> names = new ArrayList<String>();
names.add("Bob");
names.add("Jill");
names.add("Tom");
names.add("Brandon");

char index = randomGenerator.nextChar(names.size());
String anynames = names.get(index);
System.out.println("Your random name is" + anynames + "now!");

但是现在它说无法解析 randomGenerator 并且 void 方法无法返回值.关于我哪里出错的任何想法?

However now it says randomGenerator cannot be resolved and void methods cannot return a value. Any ideas on where I went wrong?

推荐答案

import java.util.*; 

public class characters 
{
    public static void main(String[] args)
    {
       Random generate = new Random();
       String[] name = {"John", "Marcus", "Susan", "Henry"};

       System.out.println("Customer: " + name[generate.nextInt(4)]);      

    }
}

看看它有多容易?我给了 4 个简单的名字,可以用单词等代替.代码中的4"代表字符串中名称的数量.这很简单.对于那些想要更短的人(我所做的只是减少间距):

See how easy it is? I gave 4 simple names which can be replaced with words and such. The "4" in the code represents the number of names in the String. This is about as simple as it gets. And for those who want it even shorter(all I did was decrease the spacing):

import java.util.*; 
public class characters{ 
public static void main(String[] args){
Random generate = new Random(); 
String[] name = {"John", "Marcus", "Susan", "Henry"};
System.out.println("Customer: " + name[generate.nextInt(4)]); }}

这篇关于如何从给定的列表中随机生成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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