如何选择范围内的随机数? [英] How do I choose a random number within a range?

查看:99
本文介绍了如何选择范围内的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个程序,要求用户输入一个单词及其长度,例如cow 3.输出是在原始单词前放置的单词中随机选择的字母。但是我的代码选择了一个不在原始单词中的随机字母。如何更改此选项只能选择给定的字母?



我尝试过的方法:



I have to create a program that asks a user to enter a word and its length for example, cow 3. The output is a randomly chosen letter in the word put in front of the original word. However my code chooses a random letter that is not in the original word. How can I change this to only choose the given letters?

What I have tried:

import java.util.Scanner; 
import java.util.Random;

public class Gibberish
{
   public static void main(String [] args) 
   {
      Scanner scnr = new Scanner(System.in);
      Random randNum = new Random();
      String wordEntered = "";
      int wordLength;
           
      System.out.println("Enter a word and its length: ");
      wordEntered = scnr.next();
      wordLength = scnr.nextInt();      
      
      char firstLetter  = wordEntered.charAt(0); //possible source of error
      String finalWord =  ((char)(randNum.nextInt(wordLength) + 'a')) + wordEntered;
      System.out.println("The gibberish word is " + finalWord + ".");
   
   }
}

推荐答案

使用 java.util.Random.nextInt(int n)方法 [ ^ ] - 它给出一个介于0和(n - 1)之间的数字,这是一个完美的字符串索引。
Use the java.util.Random.nextInt(int n) Method[^] - it gives you a number between 0 and (n - 1) which is perfect as an index into the string.


这篇关于如何选择范围内的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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