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
205 views
in Technique[技术] by (71.8m points)

java - Counting the amount of highest number in a string

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

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

1 Reply

0 votes
by (71.8m points)

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.


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

...