一道Java的题目 求编程Problem Description:Write a program that reads integers,findsthe largest of them,and counts its occurrences.Assume that the input endswith number 0.Suppose that you entered 3 5 2 5 5 5 0; the program finds thatthe largest
来源:学生作业帮助网 编辑:六六作业网 时间:2024/11/28 21:06:37
一道Java的题目 求编程Problem Description:Write a program that reads integers,findsthe largest of them,and counts its occurrences.Assume that the input endswith number 0.Suppose that you entered 3 5 2 5 5 5 0; the program finds thatthe largest
一道Java的题目 求编程
Problem Description:
Write a program that reads integers,findsthe largest of them,and counts its occurrences.Assume that the input endswith number 0.Suppose that you entered 3 5 2 5 5 5 0; the program finds thatthe largest is 5 and the occurrence count for 5 is 4.(Hint:Maintain twovariables,max and count.max stores the current max number,and count storesits occurrences.Initially,assign the first number to max and 1 to count.Compare each subsequent number with max.If the number is greater than max,assign it to max and reset count to 1.If the number is equal to max,incrementcount by 1.)
Here are sample runs of the program:
Sample 1:
Enternumbers:3 5 2 5 5 5 0
Thelargest number is 5
Theoccurrence count of the largest number is 4
Sample 2:
Enternumbers:3 6 5 4 2 4 5 4 55 0
Thelargest number is 6
Theoccurrence count of the largest number is 1
一道Java的题目 求编程Problem Description:Write a program that reads integers,findsthe largest of them,and counts its occurrences.Assume that the input endswith number 0.Suppose that you entered 3 5 2 5 5 5 0; the program finds thatthe largest
首先你读懂题没有,我帮你翻译一下:
问题描述:
编写一个程序,读取整数,找出其中最大的,并计算其出现次数.假设输入与数字0结束.假设你进入3 5 2 5 5 5 0;程序发现,最大的为5,出现次数为4. (提示:建立两个变量,最大值和计数值,最大存储当前的最大数量,并计算其出现次数,分配一个最大值和1来计算比较每个后续数,最大如果人数大于最大. ,将其分配到最大,并重置计数为1,如果数等于最大,由1递增计数.)
下面是该程序的运行示例:
示例1:
输入数字:3 5 2 5 5 5 0
最大数量为5
出现次数为4
示例2:
输入数字:3 6 5 4 2 4 5 4 5 5 0
最大数是6
出现次数为1
简单的说,问题就是随便输入一串数字,找出最大值,并且计算其出现次数!
问题搞清楚了,就来编程吧,经测试,我的代码可以正确运行:
package test01;
import java.util.Scanner;
public class TestSystemIn {
public static void main(String[] args) {
System.out.println("请输入内容,不同内容以逗号隔开,请以0结尾,以回车结束");
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
String a[] = str.split(",");
int temp = 0;
if (0 != (Integer.parseInt(a[a.length - 1]))) {
System.out.println("请以0结尾");
return;
}
for (int i = 0; i < a.length; i++) {
if (Integer.parseInt(a[i]) > temp) {
temp = Integer.parseInt(a[i]);
}
}
System.out.println("最大的为:" + temp);
int max = temp;
int times = 0;
for (int i = 0; i < a.length; i++) {
if (Integer.parseInt(a[i]) == max) {
times++;
}
}
System.out.println("出现的次数为:" + times);
}
}