计算一个字符串中最大数量的数量 [英] Counting the amount of highest number in a string
本文介绍了计算一个字符串中最大数量的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图输出用户输入中出现的最高数字的次数,例如用户输入2 4 3 4 2 4 0最高的数字是4,出现3次,不知道该怎么去做。
public static void main(String [] args){
// TODO自动生成的方法存根
扫描仪键盘=新扫描仪(System.in);
字符串编号,最后一个;
System.out.println(输入一个整数(0结束输入):);
number = keyboard.nextLine();
last = number.substring(number.length() - 1); $!
$ b while(!last.equals(0)){
System.out.println(必须以0结束输入);
number = keyboard.nextLine();
last = number.substring(number.length() - 1);
}
String [] array = number.split();
int max = Integer.MIN_VALUE,maxIndex = 0;
int count;
$ b 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(最大的数字是+ max);
解决方案
8的流,例如:
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)数数()));
System.out.println(numberMap.descendingMap()。firstEntry()。getValue());
这基本上存储每个数字,并计入 Map
。作为 Map
我们使用的是 TreeMap
,它按照升序对键进行排序。然后,我们得到它的最后一个(即最高)键,并打印相应的值,即3。
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);
}
解决方案
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.
这篇关于计算一个字符串中最大数量的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文