使用 JOptionPane 接收用户输入的若干个数字,以 0 结束。程序查找出所有
数字中数值最大的数字,并统计该数字出现的次数。例如,你输入 3 5 2 5 5 5 0;
程序找出最大数为 5 并且 5 的出现次数 is 4. (提示: 定义两个变量, max and
count. max 变量存储当前最大的数, count 变量存储该数的出现次数。)
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class Test{
public static void main(String[] args) {
int max = 0;
List<Integer> list = new ArrayList<>();
String s = JOptionPane.showInputDialog(null, "Enter a number", "输入对话框",JOptionPane.INFORMATION_MESSAGE);
int num = Integer.parseInt(s);
list.add(num);
if(num > max) {
max = num;
}
while(!s.equals("0")) {
s = JOptionPane.showInputDialog(null, "Enter a number", "输入对话框",JOptionPane.INFORMATION_MESSAGE);
num = Integer.parseInt(s);
list.add(num);
if(num > max) {
max = num;
}
}
int count = 0;
for(Integer n : list) {
if(max == n) {
count++;
}
}
JOptionPane.showMessageDialog(null,"输入的最大数为:" + max + "共出现了:" + count + "次", "结果!",JOptionPane.INFORMATION_MESSAGE);
}
}
<?php
$array=array(3,5,2,5,5,5,0);
function find_max_count($array=array())
{
$array=array_values($array);//强制性转换为索引数组
if(empty($array))
{
return false;//如果数组为空 则立刻返回false
}
$length=count($array);//统计数组长度
$max=$array[0];//取出第一个作为最大值
$count=1;//初始化设定统计次数为1
for ($i=1; $i <$length ; $i++)
{
if($array[$i]>$max)
{
$max=$array[$i];$count=1;//如果当前遍历元素大于最大值,说明要重新赋值最大值并重置统计次数为1
}elseif($array[$i]==$max)
{
$count++;//如果等于最大值说明还是它,将出现次数+1
}else
{
continue;//这说明是小于最大值的 直接跳过
}
}
return array("max"=>$max,"count"=>$count);//返回统计结果
}
var_dump(find_max_count($array));
?>
package com.examples.vertx;
import javax.swing.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
final List<Integer> data = new ArrayList<>();
String objName = null;
while (!"0".equals(objName)) {
objName = JOptionPane.showInputDialog(null,
"请输入数字",
"提示", JOptionPane.INFORMATION_MESSAGE);
data.add(Integer.valueOf(objName));
}
final Integer max = data.stream().max(Integer::compareTo).get();
final Long count = data.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream()
.max(Comparator.comparing(Map.Entry::getValue)).get().getValue();
JOptionPane.showMessageDialog(null, String.format("最大数%s,次数%s", max, count), "", JOptionPane.INFORMATION_MESSAGE);
}
}