Нахождение вхождения целого числа из массива в файл: - PullRequest
2 голосов
/ 02 мая 2020

Мне нужно выяснить, сколько раз число 50 встречается в этом массиве, который был создан из чисел в текстовом файле, а затем вывести, сколько учеников набрало 50 баллов, но я, кажется, застрял в бесконечном l oop в конце? Я должен использовать массивы, а также методы. Любая помощь будет оценена, спасибо !!

import javax.swing.JOptionPane;
import java.util.Scanner;
import java.io.*;

public class TestScores
{
   public static void main(String[] args) throws IOException
   {
      int count=0;
      int number;

      //Open the file
      File file=new File("scores.txt");
      Scanner inputFile=new Scanner(file);

      //Count the number of elements in the file 
      while(inputFile.hasNext())
      {
         number=inputFile.nextInt();
         count++;
      }

      //Close the file 
      inputFile.close();

      //Create an array      
      int[] numbers=new int[count];

      //Display the number of elements in the array 
      JOptionPane.showMessageDialog(null, count); 

      //Pass the array to the loadData method
      loadData(numbers);   

     //Pass the array to the perfectScore method
      perfectScore(numbers);
  }       

 /**
     The loadData method loads the data from the file into the array
     @param array A reference to the array
  */

 public static void loadData(int[] array) throws IOException
 {
     int index=0;
     //Open the file
     File file=new File("scores.txt");
     Scanner inputFile=new Scanner(file);
     //load the data from the file into the array
     while(inputFile.hasNext() && index<array.length)
     {
        array[index]=inputFile.nextInt();
        index++;
     }
  }

  /**
     The perfectScore method determines how many students 
     got a 50 on the exam.
     @param array A reference to the array
  */

  public static void perfectScore(int[] array)
  {
     for(int index=0; index<array.length; index++)
    {
        if(array[index]==50)
        {
           index++;
           int perfect=array[index];
           JOptionPane.showMessageDialog(null, "The number of students " +
           "who got a perfect 50 score is: "+ perfect + " students.");
        }
     }
   }  
}

Ответы [ 5 ]

4 голосов
/ 02 мая 2020
public static void perfectScore(int[] array)  {
    int count = 0;
    for(int index=0; index<array.length; index++){
       if(array[index]==50) {
         //  index++;  // don't increment this
           count++;

       }
    }
     JOptionPane.showMessageDialog(null, "The number of students " +
           "who got a perfect 50 score is: "+count + " students.");
} 
  • Не увеличивать индекс для подсчета. Увеличьте некоторую другую переменную, например count
  • , и переместите OptionPane за пределы l oop
0 голосов
/ 02 мая 2020

Вы также можете использовать Java8:

int count = IntStream.range(0, array.length).filter(index -> array[index] == 50).count();

Или ( от @ Abra ):

IntStream.of(array).filter(score -> score == 50).count();
0 голосов
/ 02 мая 2020
  • Не читайте файл дважды. Прочитайте один раз и загрузите в массив
  • Итерируйте массив и увеличьте число, если вы найдете 50
  • Наконец, отобразите сообщение.

Проблема с этим кодом заключается в том, Вы снова увеличиваете индекс, когда найдете значение 50.

0 голосов
/ 02 мая 2020

Используйте это:

public static void perfectScore(int[] arr) {

    int count = 0;

    int len = arr.length;
    for (int i = 0; i < len; i++) {
        if (arr[i] == 50)
            count++;
    }

    JOptionPane.showMessageDialog(null, "The number of students who got a perfect 50 score is: " + count + " students.");

}

Вы вызываете JOptionPane.showMessageDialog для каждого учащегося со счетом 50. Но java остановится после открытия одного диалога (Это продолжится, как только диалог закроется, но вы делают это для каждого студента с результатом 50).

0 голосов
/ 02 мая 2020

Так что в вашем блоке for - if, потому что вы даете сообщение пользователю каждый раз, когда он находит 50! Почему ты бы так поступил? Я имею в виду просто посчитать в этом блоке и в конце показать пользователю только результат! Нет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...