0

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 :(

3
  • You should read this answer again. Especially the printf at the end. Commented Jan 23, 2014 at 7:38
  • Is the use of an array absolutely mandatory? You'd better use a List implementation (ArrayList for example ): that way you are not obliged to declare its size at the beginning and you don't have to manage the index of the items you put in it. Commented Jan 23, 2014 at 7:40
  • Unfortunately I must use a array for this program. Commented Jan 23, 2014 at 7:54

4 Answers 4

1

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]);
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Hey marioosh, thanks for your input. But I'm trying to loop through using Scanner constructor, hasNextLine(), next(), and nextInt() methods. And most importantly use a try and catch for inputmismatchexception. So no list and bufferedReader :(
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

1 Comment

I managed to understand it and correctly finish my program! Thank you so much Elliott! Literally saved me from a sleepless night! I'm so happy right now!
0

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;
}

Comments

0

Enclose try catch for below code:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.