从文本文件中读取整数并将它们放入已排序的数组中

时间:2022-09-06 00:21:10

I've been scratching my head on this all day trying to figure out how to do this. I have tried multiple different ways, but I feel I've been going about this all wrong. My assignment is to read 50 integers from a .txt file and put the contents into a sorted array, then list the highest/lowest/average number, but I can hardly get past step one.

我整天都在摸不着头脑,想弄清楚如何做到这一点。我尝试过多种不同的方法,但我觉得我一直都在考虑这个问题。我的任务是从.txt文件中读取50个整数并将内容放入已排序的数组中,然后列出最高/最低/平均数,但我很难通过第一步。

These are the 50 numbers in the text file

这些是文本文件中的50个数字

64 61 169 113 81 61 206 176 39 100 22 200 128 152 59 165 67 116 165 72 26 149 58 204 188 69 203 94 96 134 83 122 192 85 62 159 35 162 95 92 126 66 66 203 187 18 132 182 181 175

64 61 169 113 81 61 206 176 39 100 22 200 128 152 59 165 67 116 165 72 26 149 58 204 188 69 203 94 96 134 83 122 192 85 62 159 35 162 95 92 126 66 66 203 187 18 132 182 181 175

In this file I've managed to get the "proj8" file to at least print.

在这个文件中,我设法得到“proj8”文件至少打印。

import java.util.Scanner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import java.io.*;

public class ect7{

  public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new FileReader("proj8.txt"));

    String line = br.readLine();

    while ((line = br.readLine()) != null) {
      System.out.println(line);
    }
    br.close();
  } 
}

In this file I've managed to get the "proj8" file to print and somewhat order them, but insanely so.

在这个文件中,我设法得到了“proj8”文件进行打印并在某种程度上对它们进行了排序,但是非常疯狂。

import java.util.Scanner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import java.io.*;

public class ect73{

public static void main(String[] args) throws IOException {

  //int [] myArr = new int[50];  
  //FileReader fr = new FileReader("proj8.txt");    
  BufferedReader br = new BufferedReader(new FileReader("proj8.txt"));
  List<String> lines = new ArrayList<String>();
  String line = null;

  //String line = br.readLine();

   while ((line = br.readLine()) != null) {
     lines.add(line);
     Collections.sort(lines);
     //System.out.println(line);
     System.out.println(lines);
   }   
   br.close();
   //return lines.toArray(new String[lines.size()]);
  }
}

I know I'm doing this all wrong but I have no idea how to do this right. I need to be able to input the .txt file into a sorted array in integer and then list the highest/lowest/average number. Any help is good help, but the more simple the code the better.

我知道我这样做是错的,但我不知道如何做到这一点。我需要能够将.txt文件输入到整数排序的数组中,然后列出最高/最低/平均数。任何帮助都是很好的帮助,但代码越简单越好。

3 个解决方案

#1


you are trying to sort lines of the file which contains several numbers separated by space. you have to split each line into numbers and for each number you have to parse it as an Integer and store those in the ArrayList. finally you can sort the ArrayList.

您正在尝试对包含由空格分隔的多个数字的文件行进行排序。你必须将每一行拆分成数字,并且对于每个数字,你必须将它解析为一个整数并将它们存储在ArrayList中。最后你可以对ArrayList进行排序。

    BufferedReader br = new BufferedReader(new FileReader("proj8.txt"));
    List<Integer> numbers = new ArrayList<Integer>();
    String line = null;

     //String line = br.readLine();

     while ((line = br.readLine()) != null) {
         String []strNumbers = line.split(" ");
         for(String strNumber : strNumbers){
             numbers.add(Integer.parseInt(strNumber));
         }

         //System.out.println(line);            
     }   
     br.close();

     Collections.sort(numbers);
     System.out.println(numbers);

#2


You're on the right track but looking at your file it looks like it contains more than one number per line so you need to handle this. You also need to convert them to numbers or they will be sorted as strings (meaning that "10" comes before "2").

你在正确的轨道上,但看着你的文件,它看起来每行包含多个数字,所以你需要处理这个。您还需要将它们转换为数字,否则它们将被排序为字符串(意味着“10”在“2”之前)。

I'm not going to give you the whole answer but here are a few methods/classes you can use to solve this:

我不打算给你完整的答案,但是这里有一些方法/类可以用来解决这个问题:

You won't have to use all of these, but they should be able to help you find a solution.

您不必使用所有这些,但他们应该能够帮助您找到解决方案。

#3


You dont have to go with complex methods all you have to do is to open the file create a scanner object. 1 for loop to construct the array from the text file 1 for loop to find the lowest/highest value and the sum of all values. then you compute the average and you output all results.

你不必使用复杂的方法,你所要做的就是打开文件创建一个扫描仪对象。 1 for循环从文本文件1 for循环中构造数组,以找到最低/最高值和所有值的总和。然后你计算平均值,然后输出所有结果。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class textToArray {

        public static void main(String[] args) throws FileNotFoundException{
        //Open the file 
        File f = new File("C:\\Users\\YOUR COMPUTER\\Desktop\\java.txt");//when the file directory contain \ you need to use escape ex "c:\\user\\desktop"
        //Create a new scanner to read the file
        Scanner s = new Scanner(f);
        //Declare an array with length of 100
        int[] array = new int[100];
        int i = 0, min, max, sum = 0;
        //Loop through the file if there is a next int to process it will continue

        for(i = 0; s.hasNextInt(); i++){
            //We store every int we read in the array
            array[i] = s.nextInt();                             
        }

        //Close the scanner object
        s.close();
        //As the for loop will stop when there is no new int to read so the i++ will stop at the number of int in the file
        //We use this number to calculate the average
        int nbInArray = i;
        //initialize min and max to the first array value which is for now empty
        min = max = array[0];
        for(int j = 0; j<nbInArray ; j++){
            //Now we test if the new value if bigger than the initial value (0 or empty) the new value will become the max
            if (array[j]>max){
                max = array[j];
                }
            //Otherwise if the the value is smaller than the initial value the new value will become the minimum
            //And so on every time we test if we have a smaller value the new one will become the min
            if (array[j]<min){
                min = array[j];
                }
            //The sum was initialised to 0 so we add every new int to it
            sum = sum + array[j];
        }


        //We compute the avg , i declared it double in case we have decimal results
        double avg = sum / nbInArray;
        //finally we print out the min, max and the average
        System.out.println("The minimum is: "+min);
        System.out.println("The maximum is: "+max);
        System.out.println("The averange is: "+avg);

}
}

#1


you are trying to sort lines of the file which contains several numbers separated by space. you have to split each line into numbers and for each number you have to parse it as an Integer and store those in the ArrayList. finally you can sort the ArrayList.

您正在尝试对包含由空格分隔的多个数字的文件行进行排序。你必须将每一行拆分成数字,并且对于每个数字,你必须将它解析为一个整数并将它们存储在ArrayList中。最后你可以对ArrayList进行排序。

    BufferedReader br = new BufferedReader(new FileReader("proj8.txt"));
    List<Integer> numbers = new ArrayList<Integer>();
    String line = null;

     //String line = br.readLine();

     while ((line = br.readLine()) != null) {
         String []strNumbers = line.split(" ");
         for(String strNumber : strNumbers){
             numbers.add(Integer.parseInt(strNumber));
         }

         //System.out.println(line);            
     }   
     br.close();

     Collections.sort(numbers);
     System.out.println(numbers);

#2


You're on the right track but looking at your file it looks like it contains more than one number per line so you need to handle this. You also need to convert them to numbers or they will be sorted as strings (meaning that "10" comes before "2").

你在正确的轨道上,但看着你的文件,它看起来每行包含多个数字,所以你需要处理这个。您还需要将它们转换为数字,否则它们将被排序为字符串(意味着“10”在“2”之前)。

I'm not going to give you the whole answer but here are a few methods/classes you can use to solve this:

我不打算给你完整的答案,但是这里有一些方法/类可以用来解决这个问题:

You won't have to use all of these, but they should be able to help you find a solution.

您不必使用所有这些,但他们应该能够帮助您找到解决方案。

#3


You dont have to go with complex methods all you have to do is to open the file create a scanner object. 1 for loop to construct the array from the text file 1 for loop to find the lowest/highest value and the sum of all values. then you compute the average and you output all results.

你不必使用复杂的方法,你所要做的就是打开文件创建一个扫描仪对象。 1 for循环从文本文件1 for循环中构造数组,以找到最低/最高值和所有值的总和。然后你计算平均值,然后输出所有结果。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class textToArray {

        public static void main(String[] args) throws FileNotFoundException{
        //Open the file 
        File f = new File("C:\\Users\\YOUR COMPUTER\\Desktop\\java.txt");//when the file directory contain \ you need to use escape ex "c:\\user\\desktop"
        //Create a new scanner to read the file
        Scanner s = new Scanner(f);
        //Declare an array with length of 100
        int[] array = new int[100];
        int i = 0, min, max, sum = 0;
        //Loop through the file if there is a next int to process it will continue

        for(i = 0; s.hasNextInt(); i++){
            //We store every int we read in the array
            array[i] = s.nextInt();                             
        }

        //Close the scanner object
        s.close();
        //As the for loop will stop when there is no new int to read so the i++ will stop at the number of int in the file
        //We use this number to calculate the average
        int nbInArray = i;
        //initialize min and max to the first array value which is for now empty
        min = max = array[0];
        for(int j = 0; j<nbInArray ; j++){
            //Now we test if the new value if bigger than the initial value (0 or empty) the new value will become the max
            if (array[j]>max){
                max = array[j];
                }
            //Otherwise if the the value is smaller than the initial value the new value will become the minimum
            //And so on every time we test if we have a smaller value the new one will become the min
            if (array[j]<min){
                min = array[j];
                }
            //The sum was initialised to 0 so we add every new int to it
            sum = sum + array[j];
        }


        //We compute the avg , i declared it double in case we have decimal results
        double avg = sum / nbInArray;
        //finally we print out the min, max and the average
        System.out.println("The minimum is: "+min);
        System.out.println("The maximum is: "+max);
        System.out.println("The averange is: "+avg);

}
}