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



所以我正在做一个随机数生成器,用户在其中输入他们想要接收的范围外的最低值、最高值和所需数量的随机数,并试图在它给出的每个数字的开头添加一句话。它在一行新行中一个接一个地打印出结果,我想知道是否可以添加一个字符串,根据用户想要从该范围生成随机数的次数循环。

//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的计数器。查看此问答:

在Java8中,有没有一种简洁的方法可以迭代具有索引的流?

相关内容

最新更新