Tell me how it can be done.

public static void main(String[] args) { int[] num = new int[4]; try { Scanner in = new Scanner(new File("C:\\Users\\admin\\Desktop\\file.txt")); System.out.println("Вывод, с учетом замены целых четных чисел на '0':" ); for(int i = 0;i < 4; i++){ num[i] = in.nextInt(); System.out.println(num[i]); } in.close(); } catch(FileNotFoundException ex) { ex.printStackTrace(); } catch(NoSuchElementException ex){ System.out.println("Input File is incorrect..."); } } 

Closed due to the fact that off-topic participants are Roman C , AK , 0xdb , user192664, aleksandr barakin 29 Sep '18 at 8:20 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - Roman C, 0xdb, Community Spirit, aleksandr barakin
If the question can be reformulated according to the rules set out in the certificate , edit it .

    2 answers 2

    Firstly, your task does not say in what format you need to write (and then read) a file with numbers and how many numbers there should be. Therefore, it seems logical to consider some general case. Then there is no point in using an array - after all, the size is unknown in advance (and in general - why do we need an array? Just read the numbers from the file and immediately write down either the read number itself, if it is odd, or 0, if the number is even).

    Further, Scanner has a remarkable ability to tell if it still has data, so there is no need to use for , you can use while - for пока (естьЕщеДанные) { прочитать; обработать; } пока (естьЕщеДанные) { прочитать; обработать; }

    Then, starting with Java 7 (and you hardly use an older one) there is a design that allows you to work with files much more gracefully - you don’t have to write multi-story try ... catch ... finally with attachments, you can just use what is called try with resources , namely, write try (описать и открыть файл) { работать с файлом } and that's it — the file will be closed automatically.

    And one more thing - in the task it says "create a file", and you do not create it - for some reason you assume that it should already exist.

    Thus, if you do not use the new features of Java 8 (which you, it seems, have not yet studied), but to solve the problem in approximately the same style as you tried (with scanners, etc.), you get something like this code:

      public static void main(String[] args) { // Запишем файл со случайными целыми числами try ( PrintWriter out = new PrintWriter(new FileWriter("file.txt")); ) { int count = (int)((Math.random() + 0.5) * 1000); // 500 to 1500 numbers for (int i = 0; i < count; i++) { out.print((int)( (Math.random() - 0.5) * 2.0 * Integer.MAX_VALUE) + " "); if (i % 10 == 0) // 10 numbers per line out.println(); } } catch (IOException x) { System.out.println("IO error: " + x); } // Теперь прочитаем этот файл и перепишем в новый, // заменив чётные числа нулями try (Scanner in = new Scanner(new File("file.txt")); // "try с ресурсами" PrintWriter out = new PrintWriter(new FileWriter("out_file.txt"));) { System.out.println("Вывод, с учетом замены целых четных чисел на '0':"); while (in.hasNextLine()) { Scanner line = new Scanner(in.nextLine()); // Одна строка файла while (line.hasNextInt()) { // Разберем ее на числа int data = line.nextInt(); // Очередное число if (data % 2 == 0) { // Если чётное System.out.format("%d -> 0, ", data); // Чтоб было видно, что делается data = 0; // Заменим его нулём } else System.out.print(data + ", "); // Чтоб было видно, что делается out.print(data + ", "); } line.close(); // Не забывать, чтобы не было утечек out.println(); // Строка закончена -- перенос строки в вых. файл System.out.println(); // и на экране } } catch (IOException x) { System.out.println("IO error: " + x); } // И всё. Файлы закрыты } // main 
    • thank you very much. Thank. Not expected. Thank you very much - Dmitry Pavlovsky

    Provided that the file numbers are stored in the form 0 1 2 3 4 5 6 7 8 9 ... (option is far from ideal ...)

     public static void main(String[] args) { File file = new File("C:\\Users\\admin\\Desktop\\file.txt"); StringBuilder sb = new StringBuilder(); try (BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(file)))) { String[] words = br.readLine().split(" "); for (String number : words) { if (Integer.valueOf(number)%2 == 0) { sb.append(0 + " "); } else { sb.append(number).append(" "); } } FileWriter fileWriter = new FileWriter(file); fileWriter.write(sb.toString()); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } 
    • that is, only a single-line file in which numbers are separated by spaces. And you forgot to close the output file. - m. vokhm
    • @ m.vokhm Thank you, corrected the code. - Ivan Chaykin pm