简体   繁体   中英

Reading Integers from text file and storing into array

I've been having stressful issues all day on this program to read a text file for integers and storing the integers into an array. I thought I finally got the solution with the code below.

But unfortunately.. I have to loop through the file with the method hasNextLine(). Then using nextInt() to read integers from the file and store them into an array. So using scanner constructor, hasNextLine(), next(), and nextInt() methods.

Then use try and catch to determine which words are integers and which are not by using the InputMismatchException. Also a exception for blank lines in the file? Problem is I did not use a try and catch and exceptions, as I just skipped over none-ints. Also, I'm using a int array so I want to do this without list.

      public static void main(String[] commandlineArgument) {
         Integer[] array = ReadFile4.readFileReturnIntegers(commandlineArgument[0]);
         ReadFile4.printArrayAndIntegerCount(array, commandlineArgument[0]);
      }

      public static Integer[] readFileReturnIntegers(String filename) {
         Integer[] array = new Integer[1000];
         int i = 0;
        //connect to the file
         File file = new File(filename);
         Scanner inputFile = null;
         try {
            inputFile = new Scanner(file);
         } 
         //If file not found-error message
            catch (FileNotFoundException Exception) {
               System.out.println("File not found!");
            }
        //if connected, read file
         if (inputFile != null) {
         // loop through file for integers and store in array
            try {
               while (inputFile.hasNext()) {
                  if (inputFile.hasNextInt()) {
                     array[i] = inputFile.nextInt();
                     i++;
                  } 
                  else {
                     inputFile.next();
                  }
               }
            } 
            finally {
               inputFile.close();
            }
            System.out.println(i);
            for (int v = 0; v < i; v++) {
               System.out.println(array[v]);
            }
         }
         return array;
      }

      public static void printArrayAndIntegerCount(Integer[] array, String filename) {
      //print number of integers
      //print all integers that are stored in array
      }
   }

Then I'll be printing everything in my 2nd method, but that I can worry about later. :o

Example Content of Text File:

Name, Number
natto, 3
eggs, 12
shiitake, 1
negi, 1
garlic, 5
umeboshi, 1

Sample Output Goal:

number of integers in file "groceries.csv" = 6
    index = 0, element = 3
    index = 1, element = 12
    index = 2, element = 1
    index = 3, element = 1
    index = 4, element = 5
    index = 5, element = 1

Sorry for the similar question. I'm very stressed out, and even more that I was doing it all wrong... I'm completely stuck at this point :(

You can read Your file in this way.

/* using Scanner */
public static Integer[] getIntsFromFileUsingScanner(String file) throws IOException {
    List<Integer> l = new ArrayList<Integer>();
    InputStream in = new FileInputStream(file);
    Scanner s = new Scanner(in);
    while(s.hasNext()) {
        try {
            Integer i = s.nextInt();
            l.add(i);
        } catch (InputMismatchException e) {
            s.next();
        }
    }
    in.close();
    return l.toArray(new Integer[l.size()]);
}

/* using BufferedReader */
public static Integer[] getIntsFromFile(String file) throws IOException {
    List<Integer> l = new ArrayList<Integer>();
    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line;
    while ((line = reader.readLine()) != null) {
        try {
            l.add(Integer.parseInt(line.split(",")[1]));
        } catch (NumberFormatException e) {
        }
    }
    return l.toArray(new Integer[l.size()]);
}    

And with Your code:

  public static void main(String[] commandlineArgument) {
      Integer[] array = getIntsFromFileUsingScanner(commandlineArgument[0]);
      ReadFile4.printArrayAndIntegerCount(array, commandlineArgument[0]);
  }

Here is one way to meet your new requirements,

public static Integer[] readFileReturnIntegers(
    String filename) {
  Integer[] temp = new Integer[1000];
  int i = 0;
  // connect to the file
  File file = new File(filename);
  Scanner inputFile = null;
  try {
    inputFile = new Scanner(file);
  }
  // If file not found-error message
  catch (FileNotFoundException Exception) {
    System.out.println("File not found!");
  }
  // if connected, read file
  if (inputFile != null) {
    // loop through file for integers and store in array
    try {
      while (inputFile.hasNext()) {
        try {
          temp[i] = inputFile.nextInt();
          i++;
        } catch (InputMismatchException e) {
          inputFile.next();
        }
      }
    } finally {
      inputFile.close();
    }
    Integer[] array = new Integer[i];
    System.arraycopy(temp, 0, array, 0, i);
    return array;
  }
  return new Integer[] {};
}

public static void printArrayAndIntegerCount(
    Integer[] array, String filename) {
  System.out.printf(
      "number of integers in file \"%s\" = %d\n",
      filename, array.length);
  for (int i = 0; i < array.length; i++) {
    System.out.printf(
        "\tindex = %d, element = %d\n", i, array[i]);
  }
}

Outputs

number of integers in file "/home/efrisch/groceries.csv" = 6
    index = 0, element = 3
    index = 1, element = 12
    index = 2, element = 1
    index = 3, element = 1
    index = 4, element = 5
    index = 5, element = 1

Maybe you can resolve this issue by brief code as I post below.

public static List<Integer> readInteger(String path) throws IOException {
    List<Integer> result = new ArrayList<Integer>();
    BufferedReader reader = new BufferedReader(new FileReader(path));
    String line = null;
    Pattern pattern = Pattern.compile("\\d+");
    Matcher matcher = null;
    line = reader.readLine();
    String input = null;
    while(line != null) {
        input = line.split(",")[1].trim();
        matcher = pattern.matcher(input);
        if(matcher.matches()) {
            result.add(Integer.valueOf(input));
        }
        line = reader.readLine();
    }
    reader.close();
    return result;
}

Enclose try catch for below code:

try
{
   if (inputFile.hasNextInt()) {
        array[i] = inputFile.nextInt();
        i++;
   } 
   else {
        inputFile.next();
        }
}catch(Exception e)
{
    // handle the exception
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM