gpt4 book ai didi

java - 所以我正在做一个随机数生成器,并试图在每个的开头添加一个句子

转载 作者:行者123 更新时间:2023-11-30 05:55:55 36 4
gpt4 key购买 nike

所以我正在做一个随机数生成器,用户输入他们想要接收的超出范围的最低值、最高值和所需数量的随机数,并尝试在每个数字的开头添加一个句子给了我。我已经尽力在给定最低和最高值时生成“x”个数字。它在新行中一一打印出结果,我想知道是否可以添加一个字符串,该字符串根据用户想要从该范围生成随机数的次数进行循环。

//This java utility was used to allow the program to choose random number.
import java.util.Random;
//This java utility was used to allow the program to allow the user to input requested data.
import java.util.Scanner;
import java.util.function.IntConsumer;

class Main {

public static void main(String[] args) {

/*
* A welcoming message was added to give the user information on what the
* program was created for. The program asks for the user to choose a range and
* to input the lowest number in the range, highest number in range, and how
* many results should the program print
*/

System.out.println("Hello, this program will compute a set");
System.out.println("amount of random numbers in the given range.");
System.out.println("");

/*
* This set of code asks the user to give the value of the lowest and highest
* integer in their range and translates the string into an integer using
* Integer.parseInt(lower/higherLimit). This allows the computer to understand
* the actual value of the number given. It then takes the value added and puts
* in into the variables of 'min' and 'max' for the lowest and highest numbers
* given respectively.
*/

Scanner input = new Scanner(System.in);
System.out.print("Enter lower limit of the range:");
String lowerLimit = input.nextLine();
int min = Integer.parseInt(lowerLimit);

Scanner input1 = new Scanner(System.in);
System.out.print("Enter higher limit of the range:");
String higherLimit = input.nextLine();
int max = Integer.parseInt(higherLimit);

/*
*
*/
Scanner input3 = new Scanner(System.in);
System.out.print("How many numbers shall I print:");
String amountPrinted = input3.nextLine();
int amount = Integer.parseInt(amountPrinted);

int amount1 = amount;
int min1 = min;
int max1 = max;
{
Random random = new Random();

random.ints(amount1, min1, max1).sorted().forEach(System.out::println);


}

}
}

最佳答案

我认为你必须为此使用 lambda 表达式。简单的方法引用无法完全处理它。

   public static void main( String[] args ) {
int amount1 = 10;
int min1 = 3;
int max1 = 18;
Random random = new Random();
random.ints( amount1, min1, max1 ).sorted()
.forEach( i -> System.out.println( "Your number is " + i ) );
}

有几种方法可以为其添加索引(计数器)。这是一个简单的例子,但它有点滥用 Random 类。

  IntStream.range( 0, amount1 ).forEach( i -> 
System.out.println( "Rng #" + i + " is " +
(new Random().nextInt( max1-min1 ) + min1 )) );

您还可以使用AtomicInteger之类的内容添加计数器。请参阅此问题和答案:

Is there a concise way to iterate over a stream with indices in Java 8?

关于java - 所以我正在做一个随机数生成器,并试图在每个的开头添加一个句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53199734/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com