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);
}
}
3 个解决方案
#1
2
int secondLargest = 0;
.....
for (..) {
....
if (c % 3 == 0) {
if (c >= max) {
secondLargest = max;
max = c;
}
if (c >= secondLargest && c < max) {
secondLargest = c;
}
}
....
}
#2
2
You just need to keep 2 variables, one for maximum and another for second_maximum and update them appropriately.
您只需要保留2个变量,一个用于最大值,另一个用于second_maximum并适当地更新它们。
For a more general approach, take a look at selection algorithms
有关更一般的方法,请查看选择算法
#3
0
Below code will work
import java.util.Scanner;
public class Practical4 {
public static void main(String a[]) {
int max = 0, second_max = 0, temp, numbers;
Scanner scanner = new Scanner(System.in);
System.out.println("How many numbers do you want to enter?");
numbers = scanner.nextInt();
System.out.println("Enter numbers:");
for (int i = 0; i < numbers; i++) {
if (i == 0) {
max = scanner.nextInt();
} else {
temp = scanner.nextInt();
if (temp > max) {
second_max = max;
max = temp;
}
else if(temp>second_max)
{
second_max=temp;
}
}
}
scanner.close();
System.out.println("Second max number is :" + second_max);
}
}
#1
2
int secondLargest = 0;
.....
for (..) {
....
if (c % 3 == 0) {
if (c >= max) {
secondLargest = max;
max = c;
}
if (c >= secondLargest && c < max) {
secondLargest = c;
}
}
....
}
#2
2
You just need to keep 2 variables, one for maximum and another for second_maximum and update them appropriately.
您只需要保留2个变量,一个用于最大值,另一个用于second_maximum并适当地更新它们。
For a more general approach, take a look at selection algorithms
有关更一般的方法,请查看选择算法
#3
0
Below code will work
import java.util.Scanner;
public class Practical4 {
public static void main(String a[]) {
int max = 0, second_max = 0, temp, numbers;
Scanner scanner = new Scanner(System.in);
System.out.println("How many numbers do you want to enter?");
numbers = scanner.nextInt();
System.out.println("Enter numbers:");
for (int i = 0; i < numbers; i++) {
if (i == 0) {
max = scanner.nextInt();
} else {
temp = scanner.nextInt();
if (temp > max) {
second_max = max;
max = temp;
}
else if(temp>second_max)
{
second_max=temp;
}
}
}
scanner.close();
System.out.println("Second max number is :" + second_max);
}
}