我不确定如何使程序随机将输入放置到数组中 [英] I'm not sure how to make my program randomly place input into an array

查看:77
本文介绍了我不确定如何使程序随机将输入放置到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/**
 * Write a description of class RandomArray here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
import java.util.Scanner;
import java.util.Random;
public class RandomArray
{
   
    public RandomArray()
    {
        
        String[] array;
        array = new String[10];
        Scanner input = new Scanner(System.in);
        Random rand = new Random();
        int random = rand.nextInt(11);
        
        
        for (int i=0; i < (array.length); i++) {
            System.out.print("Enter a country: ");
            String country = input.next();
             if (array[random] == null)
        array[random] = country;
        else
        array[random] = array[random];
            
        }
        
       
        
         for (String country: array)
        System.out.print(country + ",");

推荐答案

如果我理解正确的问题,则希望对包含国家/地区的数组进行改组.一种解决方案是将数组转换为ArrayList,然后使用
If I understand the question correct, you want the array with the countries to shuffeled. A solution would be to convert the array to an ArrayList and then use
Collections.shuffle(ArrayList list);



小例子:



Little example:

public class ShuffleTest {
    public static void main(String[] args) throws Exception {
		String[] stringArray = { "A", "E", "I", "O", "U" };
		ArrayList<String> list = new ArrayList<String>();
		for(String s : stringArray)
			list.add(s);
		Collections.shuffle(list);
		String[] randomStringArray = list.toArray(new String[list.size()]);
		for(String s2 : randomStringArray)
			System.out.println(s2);
	}
}


首先,我创建一个包含一些值的String数组.之后,我将其转换为ArrayList(可能有更好的方法将数组转换为ArrayList)并使用Collections.shuffle(list);.洗牌.如果需要将字符串放在数组而不是ArrayList中,则可以使用toArray()方法将ArrayList转换为数组.

莫里茨


First I create a String array with some values in it. After that I convert it to an ArrayList (There''s probably a better way for converting array''s to ArrayList''s) and use Collections.shuffle(list); to shuffle it. If you need the string to be in an array instead of an ArrayList you can use the toArray() method to convert the ArrayList to an array.

Moritz


这篇关于我不确定如何使程序随机将输入放置到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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