java inputs an array of Numbers of outputs the maximum and minimum values of the array

  • 2020-06-12 09:04:13
  • OfStack

1. Demand analysis:

1, 1 input array -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - "program to receive 1 set of input arrays, no clear how much this set of array
2, an array of Numbers -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "the received array only Numbers
The output receives the maximum and minimum values of the array

2. Technical Difficulties

1. How to get an array of Numbers from user input?
You can use the BufferedReader class: Read text from a character input stream and buffer individual characters for efficient reading of characters, arrays, and rows.
2. How to get the maximum and minimum values?

The easiest way to do this is to iterate over the groups

Code implementation:


package com.itheima;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

/**
 * 6 ,   The input 1 An array of Numbers that prints the maximum and minimum values of the array 
 * 
 * @author 281167413@qq.com
 */

public class Test6 {

	public static void main(String[] args) throws IOException {
		System.out.println(" Please enter the 1 Group number: ");
		//  Create an input stream object 
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				System.in));
		//  read 1 Line information 
		String input = reader.readLine();
		
		//  Converts to an array with a space delimiter 
		String[] numbers = input.split(" ");
		int[] values = new int[numbers.length];
		for (int j = 0; j < numbers.length; j++) {
			values[j] = Integer.parseInt(numbers[j]);
		}
		numbers = null; //  recycling numbers Array of resources 

		//  Gets the maximum and minimum values in the received array 
		//  Getting the maximum value and getting the minimum value are written as two functions, so you're doing multiple traversals 1 Traversing the array is less efficient and more extensible 
		System.out.printf("MAX:%d, MIN:%d\n", getMax(values), getMin(values));
	}

	public static int getMax(int[] values) {
		int tmp = Integer.MIN_VALUE;

		if (null != values) {
			tmp = values[0];
			for (int i = 0; i < values.length; i++) {
				if (tmp < values[i]) {
					tmp = values[i];
				}
			}
		}

		return tmp;
	}

	public static int getMin(int[] values) {
		int tmp = Integer.MIN_VALUE;

		if (null != values) {
			tmp = values[0];
			for (int i = 0; i < values.length; i++) {
				if (tmp > values[i]) {
					tmp = values[i];
				}
			}
		}

		return tmp;
	}
}


Related articles: