Всем добрый вечер. Попытки пройти эту задачу продолжаются...
После множества исправлений, код заметно уменьшился, но по-прежнему не проходит проверку по 3 и 4 пункту, хотя вроде все работает с разными вариантами параметров, в том числе без них.
Прошу помочь найти сценарий запуска программы, при котором она работает неверно, либо же ошибку в коде.
Сам я уже перепробовал вроде бы все варианты, но такого, который бы не сработал так и не нашел.
У меня создалось впечатление, что проблема не в ветке обновления или удаления строки, а уровнем выше, при поиске id или где-то еще.
package com.javarush.task.task18.task1828;
/*
Прайсы 2
*/
import java.io.*;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = null;
byte file_bytes[] = null;
s = reader.readLine();
FileInputStream fi = new FileInputStream(s);
while (fi.available() > 0) {
file_bytes = new byte[fi.available()];//основной массив файла
fi.read(file_bytes);
}
int id_length = 0;//длина поля id
int y = 0;//начало поиска поля id в файле
int st = -10000;//переменная для индекса начала поля id в файле
int start = 0; // индекс начала откуда делать изменения или удаление строки
int end_stroke = 0; //индекс конца строки
FileOutputStream fo = null;
byte id[];//id
//ищем переданный id в файле сравнивая побайтово то, что передали с тем, что есть в файле
try {
if (args[1].length() > 0 && args[1].length() <= 8) {
while (args[1].length() < 8) {
args[1] = args[1] + " ";
}
id = args[1].getBytes();
if (file_bytes != null) {
for (y = 0; y < file_bytes.length; y++) {
if (y == 0 || file_bytes[y - 1] == 10) {//смотрим всегда id-шник, это первые 8 символов в строке
for (int jk = y; jk < (y + args[1].length()); jk++) {
if (file_bytes[jk] == id[id_length]) {
id_length++;//увеличиваем длину id, если байты совпадают
if (id_length == args[1].length()) {
st = y;//1ый символ из id
break;
}
} else {
id_length = 0;
break;//переход на следующую строку
}
}
}
if (st != -10000) {
break;
}
}
} else id_length = 0;
}
}catch (ArrayIndexOutOfBoundsException e) {}
int end_file = 0;//индекс конца файла
try {
if (id_length != 0) {
if (args[0].equals("-u") && args[2].length() > 0 && args[3].length() > 0 && args[4].length() > 0) { //update
start = st + 8;//прибавляем к началу 8, потому что длина поля id - 8 символов
while (args[2].length() < 30) {
args[2] = args[2] + " ";
}
while (args[3].length() < 8) {
args[3] = args[3] + " ";
}
while (args[4].length() < 4) {
args[4] = args[4] + " ";
}
if (args[2].length() > 30) args[2] = args[2].substring(0, 30);
if (args[3].length() > 8) args[3] = args[3].substring(0, 8);
if (args[4].length() > 4) args[4] = args[4].substring(0, 4);
byte prName[] = args[2].getBytes();
int h = 0;
int ii = start;
for (h = 0; h < args[2].length(); h++) {
file_bytes[ii] = prName[h];
ii++;
}
byte price[] = args[3].getBytes();
for (h = 0; h < args[3].length(); h++) {
file_bytes[ii] = price[h];
ii++;
}
byte quantity[] = args[4].getBytes();
for (h = 0; h < args[4].length(); h++) {
file_bytes[ii] = quantity[h];
ii++;
}
//запись в файл окончательного массива
fo = new FileOutputStream(s);
for (int jh = 0; jh <= file_bytes.length; jh++) {
if (file_bytes[jh] != -2)
fo.write(file_bytes[jh]);
}
} else if (args[0].equals("-d")) {//delete
if (args.length == 2) {
start = y;
for (int ll = start; ll < file_bytes.length; ll++) {
if ((file_bytes[ll] == 13 && file_bytes[ll + 1] == 10)) {
end_stroke = ll;
break;
} else if (ll == (file_bytes.length - 1)) end_stroke = file_bytes.length;
}
if (end_stroke == file_bytes.length && start != 0) {//последняя строка
end_file = end_stroke;
//перед последней строкой есть 2-3 символа переноса предыдущей строки, которые тоже надо удалить
if (file_bytes[start - 3] == 13 || file_bytes[start - 3] == 10) file_bytes[start - 3] = -2;
file_bytes[start - 2] = -2;
file_bytes[start - 1] = -2;
} else if (end_stroke != file_bytes.length && start == 0)//первая строка
end_file = end_stroke + 2;
else if (end_stroke == file_bytes.length && start == 0)//единственная строка в файле
end_file = end_stroke;
else {
end_file = end_stroke + 2;//строка посередине
}
for (int u = start; u < end_file; u++) {
file_bytes[u] = -2;
}
//запись в файл окончательного массива
fo = new FileOutputStream(s);
for (int ii = 0; ii <= file_bytes.length; ii++) {
if (file_bytes[ii] != -2)
fo.write(file_bytes[ii]);
}
}
}
}
} catch (ArrayIndexOutOfBoundsException e) {}
reader.close();
fi.close();
if (fo != null) fo.close();
}
}
package com.javarush.task.task18.task1828;
/*
Прайсы 2
*/
import java.io.*;
public class Solution {
/*public static byte b[];//основной массив файла
public static BufferedReader reader = null;
public static FileInputStream fi = null;
public static String s = null;*/
public static void main(String[] args) throws IOException {
//readFile();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = null;
byte file_bytes[] = null;
s = reader.readLine();
FileInputStream fi = new FileInputStream(s);
while (fi.available() > 0) {
file_bytes = new byte[fi.available()];//основной массив файла
fi.read(file_bytes);
}
int id_length = 0;//длина поля id
int y = 0;//начало поиска поля id в файле
int st = -10000;//переменная для индекса начала поля id в файле
int start = 0; // индекс начала откуда делать изменения или удаление строки
int end_stroke = 0; //индекс конца строки
FileOutputStream fo = null;
byte id[];//id
//ищем переданный id в файле сравнивая побайтово то, что передали с тем, что есть в файле
try {
if (args[1].length() > 0 && args[1].length() <= 8) {
while (args[1].length() < 8) {
args[1] = args[1] + " ";
}
id = args[1].getBytes();
if (file_bytes != null) {
for (y = 0; y < file_bytes.length; y++) {
if (y == 0 || file_bytes[y - 1] == 10) {//смотрим всегда id-шник, это первые 8 символов в строке
for (int jk = y; jk < (y + args[1].length()); jk++) {
if (file_bytes[jk] == id[id_length]) {
id_length++;//увеличиваем длину id, если байты совпадают
if (id_length == args[1].length()) {
st = y;//1ый символ из id
break;
}
} else {
id_length = 0;
break;//переход на следующую строку
}
}
}
if (st != -10000) {
break;
}
}
} else id_length = 0;
}
}catch (ArrayIndexOutOfBoundsException e) {}
int end_file = 0;//индекс конца файла
try {
if (id_length != 0) {
if (args[0].equals("-u") && args[2].length() > 0 && args[3].length() > 0 && args[4].length() > 0) { //update
start = st + 8;//прибавляем к началу 8, потому что длина поля id - 8 символов
while (args[2].length() < 30) {
args[2] = args[2] + " ";
}
while (args[3].length() < 8) {
args[3] = args[3] + " ";
}
while (args[4].length() < 4) {
args[4] = args[4] + " ";
}
if (args[2].length() > 30) args[2] = args[2].substring(0, 30);
if (args[3].length() > 8) args[3] = args[3].substring(0, 8);
if (args[4].length() > 4) args[4] = args[4].substring(0, 4);
byte prName[] = args[2].getBytes();
int h = 0;
int ii = start;
for (h = 0; h < args[2].length(); h++) {
file_bytes[ii] = prName[h];
ii++;
}
byte price[] = args[3].getBytes();
for (h = 0; h < args[3].length(); h++) {
file_bytes[ii] = price[h];
ii++;
}
byte quantity[] = args[4].getBytes();
for (h = 0; h < args[4].length(); h++) {
file_bytes[ii] = quantity[h];
ii++;
}
//запись в файл окончательного массива
fo = new FileOutputStream(s);
for (int jh = 0; jh <= file_bytes.length; jh++) {
if (file_bytes[jh] != -2)
fo.write(file_bytes[jh]);
}
} else if (args[0].equals("-d")) {//delete
if (args.length == 2) {
start = y;
for (int ll = start; ll < file_bytes.length; ll++) {
if ((file_bytes[ll] == 13 && file_bytes[ll + 1] == 10)) {
end_stroke = ll;
break;
} else if (ll == (file_bytes.length - 1)) end_stroke = file_bytes.length;
}
if (end_stroke == file_bytes.length && start != 0) {//последняя строка
end_file = end_stroke;
if (file_bytes[start - 3] == 13 || file_bytes[start - 3] == 10) file_bytes[start - 3] = -2;
file_bytes[start - 2] = -2;
file_bytes[start - 1] = -2;
} else if (end_stroke != file_bytes.length && start == 0)//первая строка
end_file = end_stroke + 2;
else if (end_stroke == file_bytes.length && start == 0)//единственная строка в файле
end_file = end_stroke;
else {
end_file = end_stroke + 2;//строка посередине
}
for (int u = start; u < end_file; u++) {
file_bytes[u] = -2;
}
//запись в файл окончательного массива
fo = new FileOutputStream(s);
for (int ii = 0; ii <= file_bytes.length; ii++) {
if (file_bytes[ii] != -2)
fo.write(file_bytes[ii]);
}
}
}
}
} catch (ArrayIndexOutOfBoundsException e) {}
reader.close();
fi.close();
if (fo != null) fo.close();
}
/*public static void readFile() throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
s = reader.readLine();
fi = new FileInputStream(s);
int start = 0, end = 0;
while (fi.available() > 0) {
fi.read(b);
}
}*/
}