簡體   English   中英

從文本文件讀取整數並將其存儲到數組中

[英]Reading Integers from text file and storing into array

我整天在程序上遇到壓力大的問題,需要讀取整數的文本文件並將整數存儲到數組中。 我以為我終於有了下面的代碼解決方案。

但不幸的是..我必須使用hasNextLine()方法遍歷文件。 然后使用nextInt()從文件中讀取整數並將其存儲到數組中。 因此,使用掃描儀構造函數,hasNextLine(),next()和nextInt()方法。

然后使用try and catch通過使用InputMismatchException來確定哪些單詞是整數,哪些不是。 文件中的空白行也有例外嗎? 問題是我沒有使用try and catch和exceptions,只是跳過了none-ints。 另外,我正在使用一個int數組,所以我想在沒有列表的情況下執行此操作。

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

然后,我將使用第二種方法打印所有內容,但以后可能會擔心。 :○

文本文件的示例內容:

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

樣本輸出目標:

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

對不起,類似的問題。 我感到非常的壓力,甚至更多的是我做錯了所有的事情……在這一點上,我完全被困住了:(

您可以通過這種方式讀取文件。

/* 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()]);
}    

並使用您的代碼:

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

這是滿足您的新要求的一種方法,

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

輸出

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

也許您可以通過下面的簡短代碼解決此問題。

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

附上以下代碼的try catch:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM