Based on user input years, generate random numbers

2019-09-09 20:38发布

问题:

Before I state my question I have searched the questions that have already been posted and they were of some help to me, but not really what I am looking for.

For now, don't worry about the 2d array portion.

I am supposed to create a program that generates random float values based on the user input for a number of years. Let me explain.

First it asks for the user input for years; the user enters a value between 1-80 and the program checks if the entered value is between those two. (DONE)

Then, based on the user input, it will print out each year with a random value between [0.00 and 100.00] like so. Example; if user enters 3, then the output will display;

year 1: random values

year 2: random values

year 3: random values

Let's just start with that for now. I already have it to where it it asks for user input and I did have it to where it generated random values, but they were not between what I wanted.

Here is my code so far.

package name;
import java.util.*;

public class name {

public static void main(String[] args) {

        Random generator = new Random();

        inputCheck();

    }
    public static void inputCheck(){

        Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter the desired number of years: ");
        int years = keyboard.nextInt();
        System.out.println();

        while (years < 1 || years >= 80){
            System.out.print("Please enter a value for years that is greater than 1 and less than 80: ");
            years = keyboard.nextInt();
            System.out.println();
        }
    }
}

回答1:

Here you are

public class Test {

    public static void main(String[] args) {

        Random generator = new Random();

        int years = inputCheck();
        for (int i = 1; i <= years; i++) {
            System.out.println("Year " + i + ": " + generator.nextFloat() * 100);
        }
    }

    public static int inputCheck() {

        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter the desired number of years: ");
        int years = keyboard.nextInt();
        System.out.println();

        while (years < 1 || years >= 80) {
            System.out.print("Please enter a value for years that is greater than 1 and less than 80: ");
            years = keyboard.nextInt();
            System.out.println();
        }
        return years;
    }
}


回答2:

I don't see that generator being used, but aside from that, when you do you will only get an integer between zero and the given value(without manipulation of course) wha you want is a float between 0 and 100 with two decimal places, so generate the random number:

Randint=(Generator.nextFloat(100.00));

At least that is what I remember