【问题标题】:How java print a string value from a list?java如何从列表中打印字符串值?
【发布时间】:2015-02-13 20:14:11
【问题描述】:

如何从 java 的列表中打印字符串值?

我有一个包含更多四个字符串的数组。 我想随机打印列表中的一个值。

我试过了:

import java.util.Arrays;
import java.util.List;
import java.util.Random;

class Text {

    public static void main(String [] args) {

        String [] array = {"hello", "world", "coucou"};
        List <String> list = Arrays.asList(array);
        {
            System.out.println("String from the list ="+Random.array);
        }
    }
}

有人可以帮忙解析System.out.println 的语法吗?

谢谢。

【问题讨论】:

标签: java arrays random


【解决方案1】:

您可以使用Random 类生成介于 0(含)和列表长度(不含)之间的随机数,并打印该索引处的值。

Random rand = new Random();
System.out.println("String from list: " + list.get(rand.nextInt(list.size()));

【讨论】:

    【解决方案2】:

    在选择随机元素之前,您可以从[0, n) 范围内创建一个随机数,其中n 是列表的大小。

    你可以使用new Random(System.nanoTime()).nextInt(list.size())来做。

    【讨论】:

      【解决方案3】:
       public class ListExample {
      
          public static void main(String[] args) {
      
      
      
                String [] array = {"hello", "world", "coucou"};
      
               ArrayList <String> list=new ArrayList<String>();
      
      
               for(int i=0;i<array.length;i++){
                   list.add(array[i]);
               }
      
              Random rnd=new Random();
      
      
              System.out.println("String from the list ="+list.get(rnd.nextInt(array.length)));
      
              }
      
      
      }
      

      【讨论】:

        猜你喜欢
        • 2022-11-30
        • 1970-01-01
        • 1970-01-01
        • 2021-04-09
        • 1970-01-01
        • 1970-01-01
        • 2022-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多