如何使用 Scanner 和 for 循环找到第二大数字(无数组)
所以我可以轻松完成找到最大数字的任务,然后如果可以除以三,则打印出来。但不知道如何从用户序列中找到第二大数字。 感谢您的任何提示!
public class SecondLargest {
public static void main(String[] args) {
int max = 0;
Scanner scan = new Scanner(System.in);
System.out.println("How many numbers?");
int n = scan.nextInt();
System.out.println ("Write numbers: ");
for(int i=0; i<n; i++){
int c = scan.nextInt();
if(c>=max && c%3 == 0){
max = c;
}
else
System.out.println("There is no such number.");
}
System.out.println(max);
}
}
So I can easily accomplish task to find largest number and then if can be divided by three, print out. But do not know how to find second largest number from users sequence.
Thanks for any hints!
public class SecondLargest {
public static void main(String[] args) {
int max = 0;
Scanner scan = new Scanner(System.in);
System.out.println("How many numbers?");
int n = scan.nextInt();
System.out.println ("Write numbers: ");
for(int i=0; i<n; i++){
int c = scan.nextInt();
if(c>=max && c%3 == 0){
max = c;
}
else
System.out.println("There is no such number.");
}
System.out.println(max);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只需要保留 2 个变量,一个用于最大值,另一个用于 secondary_maximum 并适当更新它们。
如需更通用的方法,请查看选择算法
You just need to keep 2 variables, one for maximum and another for second_maximum and update them appropriately.
For a more general approach, take a look at selection algorithms