In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
Example:
HighAndLow("1 2 3 4 5") // return "5 1"
HighAndLow("1 2 -3 4 5") // return "5 -3"
HighAndLow("1 9 3 4 -5") // return "9 -5"
代码:
import java.util.Arrays; public class Kata { //方法一 public static String HighAndLow(String numbers) { numbers=numbers.replaceAll(" ",","); String[] a=numbers.split(","); int[] arr=new int[a.length]; for(int i=0;i<a.length;i++){ arr[i]=Integer.parseInt(a[i]); } Arrays.sort(arr); numbers=arr[arr.length-1]+" "+arr[0]; return numbers; } public static String HighAndLow2(String numbers) { int min = Arrays.stream(numbers.split(" ")) .mapToInt(i -> Integer.parseInt(i)) .min() .getAsInt(); int max = Arrays.stream(numbers.split(" ")) .mapToInt(i -> Integer.parseInt(i)) .max() .getAsInt(); return String.format("%d %d", max, min); } public static void main(String[] args) { String numbers="8 3 -5 42 -1 0 0 -9 4 7 4 -4"; System.out.println(HighAndLow(numbers)); System.out.println(HighAndLow2(numbers)); } }