Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

java - Finding random index

I'm new to Java, I have created an array of 15 random integers and I have found the minimum and maximum value. I now need to concatenate the index of the maximum and minimum value.

package homework7;

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

/**
 *
 * @author a
 */
public class Homework7 {

    public static void main(String[] args) {
        // Name and Homework Number 
        System.out.println("A" + " 
Homework 7");

        int[] numbers = new int[15];
        //Generates 15 Random Numbers in the range 1 - 1000
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = (int) (Math.random() * 1000 - 1);
        }//end for loop
        System.out.println("
Contents of the Array:
" + Arrays.toString(numbers));

        // Calling getMax() method for getting max value
        int max = getMax(numbers);
        System.out.println("
Maximum Value " + max + " is located at index ");

        // Calling getMin() method for getting min value
        int min = getMin(numbers);
        System.out.println("Minimum Value " + min + " is located at index ");

    }

    // Method for getting the maximum value
    public static int getMax(int[] inputArray) {
        int maxValue = inputArray[0];
        for (int i = 1; i < inputArray.length; i++) {
            if (inputArray[i] > maxValue) {
                maxValue = inputArray[i];
            }
        }
        return maxValue;
    }

    // Method for getting the minimum value
    public static int getMin(int[] inputArray) {
        int minValue = inputArray[0];
        for (int i = 1; i < inputArray.length; i++) {
            if (inputArray[i] < minValue) {
                minValue = inputArray[i];
            }
        }
        return minValue;

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

add a variable to mark the i , when you get the new min/max value in if block mark the i .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...