2017-07-04 6 views
0

私はJavaでプログラミングを始めました。私はプログラムが実行されるときに記入できるxインデックスを使用して自分の配列を作成するためのコードを書いていました。したがって、プログラムを実行すると、x = 5と言うことができ、5つのインデックス(たとえば5,2,7,4,7)を入力します。プログラムは最大値を見つけて印刷します。私は私のプログラムがmaxValueが配列に何回も印刷されるようにすることができるかどうか疑問に思っていました。上記の例では2つになります。私はちょうどこれを行う方法を見つけるように見えることができません。Javaの配列から複数の最大値を出力する方法

これは私がこれまで持っているコードです:

import java.util.*; 

public class oefeningen { 

static void maxValue(int[] newArray){//this method decides the largest number in the array 

    int result = newArray[0]; 
    for (int i=1; i<newArray.length; i++){ 
     if (newArray[i] > result){ 
      result = newArray[i]; 
     } 
    } 
     System.out.println("The largest number is: " +result); 
} 

public static void main(String[] args) { 

    Scanner keyboard = new Scanner(System.in); 

    int x; //this is the main part of the array 
    System.out.println("Please enter size of array:"); 
    x = keyboard.nextInt(); 
    int[] newArray = new int[x]; 

    for (int j=1; j<=x; j++){//this bit is used for manually entering numbers in the array 
     System.out.println("Please enter next value:"); 
     newArray[j-1] = keyboard.nextInt(); 
    } 
    maxValue(newArray); 
} 
} 
+1

「newArray [i] == result」のときにカウントしたカウンタ変数を追加し、結果を別のものに変更すると1にリセットされます。 –

+0

カウンタを追加し、現在の最大値に等しい要素を見つけるたびにカウンタをインクリメントします。現在の最大値が変更されるたびに1にリセットします。あなたは自分でそれを理解することができるはずです –

+0

これは他の質問と重複しているか分かりません...この質問は「どのように最大値に等しい項目の数を数えることができますか? - リンクされた質問は、要素を数えることとは関係ありません... – pacifier21

答えて

0

はちょうどそれが配列で

public int checkAmountOfValuesInArray(int[] array, int val) { 
     int count = 0; 
     for (int i = 0; i < array.length; i++) { 
      if (array[i]==val) count++; 
     } 
     return count; 
} 

またはあなたがすべてを行いたい場合に表示された回数をカウントするように配列し、任意の値を渡します1つのループ:

static void maxValue(int[] newArray) {//this method decides the largest number in the array 
     int result = newArray[0]; 
     int count = 1; 

     for (int i = 1; i < newArray.length; i++) { 
      if (newArray[i] > result) { 
       result = newArray[i]; 
       count = 1; 
      } else if (newArray[i] == result) { 
       count++; 
      } 
     } 
     System.out.println("The largest number is: " + result+ ", repeated: " + count + " times"); 
    } 
1

maxValue関数内で追跡し、毎回カウンタをリセットすることができます新しい最大値が発見されました。

static void maxValue(int[] newArray){//this method decides the largest number in the array 

    int count = 0; 
    int result = newArray[0]; 
    for (int i=1; i<newArray.length; i++){ 
     if (newArray[i] > result){ 
      result = newArray[i]; 
      // reset the count 
      count = 1; 
     } 
     // Check for a value equal to the current max 
     else if (newArray[i] == result) { 
      // increment the count when you find another match of the current max 
      count++; 
     } 
    } 
    System.out.println("The largest number is: " +result); 
    System.out.println("The largest number appears " + count + " times in the array"); 
} 
関連する問題