Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to output the amount of times the highest number appears in the user input for example user inputs 2 4 3 4 2 4 0 the highest number is 4 and it appears 3 times, not sure how to go about it.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner keyboard = new Scanner(System.in);

    String number, last;

    System.out.println("Enter an interger (0 ends the input): ");
    number = keyboard.nextLine();
    last = number.substring(number.length() - 1);

    while(!last.equals("0")){
        System.out.println("Must end the input with a 0: ");
        number = keyboard.nextLine();
        last = number.substring(number.length() - 1);
    }

    String[] array = number.split(" ");

    int max = Integer.MIN_VALUE, maxIndex = 0;

    int count;

    for (int i = 0; i < array.length; i++) {
         if (Integer.parseInt(array[i]) > max) {
             max = Integer.parseInt(array[i]);
             maxIndex = i;
         }
    }
    //String repeat = number.);
    System.out.println("The largest number is " + max);
}
See Question&Answers more detail:os

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

1 Answer

You can do it using Java 8's streams, e.g.:

String number = "2 4 3 4 2 4 0";
String[] array = number.split(" ");
TreeMap<Integer,Long> numberMap = Arrays.stream(array)
    .map(s -> Integer.parseInt(s))
    .collect(Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting()));
System.out.println(numberMap.descendingMap().firstEntry().getValue());

This basically stores each number and it's count into a Map. As the Map we are using is TreeMap, it sorts the keys in ascending order. We then get the last (i.e. highest) key from it and print the corresponding value which is 3.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...