スキャナとforループ(なし配列)を使用して、二番目に大きい番号を検索する方法
-
21-09-2019 - |
質問
私は3、プリントアウトによって分けることができるならば、簡単に最大数を見つけるために、タスクを達成することができそう。しかし、ユーザーの配列から二番目に大きい数を確認する方法がわかりません。 任意のヒントをありがとう!
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);
}
}
解決
int secondLargest = 0;
.....
for (..) {
....
if (c % 3 == 0) {
if (c >= max) {
secondLargest = max;
max = c;
}
if (c >= secondLargest && c < max) {
secondLargest = c;
}
}
....
}
他のヒント
あなただけの2つの変数、second_maximumの最大のための1つ、別のを維持し、それらを適切に更新する必要があります。
は、より一般的なアプローチについては、選択アルゴリズムの
を見てみましょう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);
}
}
所属していません StackOverflow