НЕПРИНЯТЫЕ РЕШЕНИЯ.
package com.javarush.test.level18.lesson10.bonus02;
/* Прайсы
CrUD для таблицы внутри файла
Считать с консоли имя файла для операций CrUD
Программа запускается со следующим набором параметров:
-c productName price quantity
Значения параметров:
где id - 8 символов
productName - название товара, 30 chars (60 bytes)
price - цена, 8 символов
quantity - количество, 4 символа
-c - добавляет товар с заданными параметрами в конец файла, генерирует id самостоятельно, инкрементируя максимальный id, найденный в файле
В файле данные хранятся в следующей последовательности (без разделяющих пробелов):
id productName price quantity
Данные дополнены пробелами до их длины
Пример:
19846 Шорты пляжные синие 159.00 12
198478 Шорты пляжные черные с рисунко173.00 17
19847983Куртка для сноубордистов, разм10173.991234
*/
/*
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public class Solution
{
public static void main(String[] args) throws Exception {
if (args[0].equals("-c")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
boolean isFinishing = true;
if (!(new File(fileName).exists())) isFinishing = false;
String amount = prepareAmmount(args);
String price = preparePrice(args);
String productName = prepareProductName(args);
String id = generateId(isFinishing, fileName);
String productToWrite = id + productName + price + amount;
File file = new File(fileName);
FileWriter fr = new FileWriter(file, isFinishing);
if (isFinishing) fr.write("\r\n");
fr.write(productToWrite); //без закрытия этого потока файл не запишется
fr.close();
reader.close();
}
}
private static String generateId(boolean isFinishing, String fileName) throws IOException {
String id;
if (isFinishing) {
String line;
BufferedReader idReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), StandardCharsets.UTF_8));
ArrayList<String> list = new ArrayList<>();
while ((line = idReader.readLine()) != null) {
list.add(line);
}
int[] listOfId = new int[list.size()]; //здесь будет список ID
int x = 0;
for (String s : list) {
char[] ch = s.toCharArray(); //здесь будет ID по символам
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 8; i++) {
builder.append(Character.toString(ch[i]));
}
listOfId[x++] = Integer.parseInt(builder.toString().trim());
}
int maxId = 0;
for (int aListOfId1 : listOfId) {
if (maxId < aListOfId1) maxId = aListOfId1;
}
id = String.valueOf(maxId + 1);
//
//if (maxId >= 99999899) maxId = 1;
//while (true) {
//boolean isEqual = false;
//id = String.valueOf((int) ((Math.random() * 100) + maxId));
//for (int aListOfId : listOfId) {
//if (Integer.parseInt(id) == aListOfId) isEqual = true;
//}
//if (!isEqual) break;
//}
//idReader.close();
//
}
else id = String.valueOf(1);
if (id.length() < 8) {
StringBuilder builder = new StringBuilder();
builder.append(id);
for (int i = id.length(); i < 8; i++) {
builder.append(" ");
}
id = builder.toString();
}
return id.substring(0, 8);
}
private static String prepareProductName(String[] args) {
StringBuilder builder = new StringBuilder();
for (int i = 1; i < args.length - 2; i++) {
builder.append(args[i]);
}
String productName = builder.toString().trim();
if (productName.length() < 30) {
StringBuilder st = new StringBuilder();
st.append(productName);
for (int i = productName.length(); i < 30; i++) {
st.append(" ");
}
productName = st.toString();
}
else if (productName.length() > 30) {
StringBuilder st = new StringBuilder();
char[] ch = productName.toCharArray();
for (int i = 0; i < 30; i++) {
st.append(Character.toString(ch[i]));
}
productName = st.toString();
}
return productName.substring(0, 30);
}
private static String prepareAmmount(String[] args) {
String amount = args[args.length - 1];
if (amount.length() < 4) {
StringBuilder st = new StringBuilder();
st.append(amount);
for (int i = amount.length(); i < 4; i++) {
st.append(" ");
}
amount = st.toString();
}
else if (amount.length() > 4) {
StringBuilder st = new StringBuilder();
char[] ch = amount.toCharArray();
for (int i = amount.length() - 4; i < amount.length(); i++) {
st.append(Character.toString(ch[i]));
}
amount = st.toString();
}
return amount.substring(0, 4);
}
private static String preparePrice(String[] args) {
String price = args[args.length - 2];
if (price.length() < 8) {
StringBuilder st = new StringBuilder();
st.append(price);
for (int i = price.length(); i < 8; i++) {
st.append(" ");
}
price = st.toString();
}
else if (price.length() > 8) {
StringBuilder st = new StringBuilder();
char[] ch = price.toCharArray();
for (int i = 0; i < 8; i++) {
st.append(Character.toString(ch[i]));
}
price = st.toString();
}
return price.substring(0, 8);
}
}
*/
import java.io.*;
import java.util.Locale;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fname = reader.readLine();
if (args.length > 0)
if (args[0].equals("-c"))
add(args, fname);
reader.close();
}
public static int getLastId(String fname) throws FileNotFoundException {
Scanner file = new Scanner(new File(fname));
int maxId = Integer.MIN_VALUE;
while (file.hasNextLine())
{
String line = file.nextLine();
int id = Integer.parseInt(line.substring(0, 8).trim());
if (id > maxId)
maxId = id;
}
file.close();
return maxId;
}
public static void add(String[] args, String fname) throws IOException {
if (args.length < 4)
return;
FileWriter file = new FileWriter(fname, true);
String id = String.format("%-8.8s", getLastId(fname) + 1);
String productName = String.format("%-30.30s", getProductNameInArgs(args));
String price = String.format("%-8.8s", String.format(Locale.US, "%.2f", Double.parseDouble(args[args.length-2])));
String quantity = String.format("%-4.4s", args[args.length-1]);
file.write(System.getProperty( "line.separator" ));
file.write(id + productName + price + quantity);
file.close();
}
public static String getProductNameInArgs(String[] args) {
StringBuilder productName = new StringBuilder();
for (int i = 1; i < args.length - 2; i++) {
productName.append(args[i]+" ");
}
return productName.toString();
}
}
package com.javarush.test.level18.lesson10.bonus02;
/* Прайсы
CrUD для таблицы внутри файла
Считать с консоли имя файла для операций CrUD
Программа запускается со следующим набором параметров:
-c productName price quantity
Значения параметров:
где id - 8 символов
productName - название товара, 30 chars (60 bytes)
price - цена, 8 символов
quantity - количество, 4 символа
-c - добавляет товар с заданными параметрами в конец файла, генерирует id самостоятельно, инкрементируя максимальный id, найденный в файле
В файле данные хранятся в следующей последовательности (без разделяющих пробелов):
id productName price quantity
Данные дополнены пробелами до их длины
Пример:
19846 Шорты пляжные синие 159.00 12
198478 Шорты пляжные черные с рисунко173.00 17
19847983Куртка для сноубордистов, разм10173.991234
*/
/*
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public class Solution
{
public static void main(String[] args) throws Exception {
if (args[0].equals("-c")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
boolean isFinishing = true;
if (!(new File(fileName).exists())) isFinishing = false;
String amount = prepareAmmount(args);
String price = preparePrice(args);
String productName = prepareProductName(args);
String id = generateId(isFinishing, fileName);
String productToWrite = id + productName + price + amount;
File file = new File(fileName);
FileWriter fr = new FileWriter(file, isFinishing);
if (isFinishing) fr.write("\r\n");
fr.write(productToWrite); //без закрытия этого потока файл не запишется
fr.close();
reader.close();
}
}
private static String generateId(boolean isFinishing, String fileName) throws IOException {
String id;
if (isFinishing) {
String line;
BufferedReader idReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), StandardCharsets.UTF_8));
ArrayList<String> list = new ArrayList<>();
while ((line = idReader.readLine()) != null) {
list.add(line);
}
int[] listOfId = new int[list.size()]; //здесь будет список ID
int x = 0;
for (String s : list) {
char[] ch = s.toCharArray(); //здесь будет ID по символам
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 8; i++) {
builder.append(Character.toString(ch[i]));
}
listOfId[x++] = Integer.parseInt(builder.toString().trim());
}
int maxId = 0;
for (int aListOfId1 : listOfId) {
if (maxId < aListOfId1) maxId = aListOfId1;
}
id = String.valueOf(maxId + 1);
//
//if (maxId >= 99999899) maxId = 1;
//while (true) {
//boolean isEqual = false;
//id = String.valueOf((int) ((Math.random() * 100) + maxId));
//for (int aListOfId : listOfId) {
//if (Integer.parseInt(id) == aListOfId) isEqual = true;
//}
//if (!isEqual) break;
//}
//idReader.close();
//
}
else id = String.valueOf(1);
if (id.length() < 8) {
StringBuilder builder = new StringBuilder();
builder.append(id);
for (int i = id.length(); i < 8; i++) {
builder.append(" ");
}
id = builder.toString();
}
return id.substring(0, 8);
}
private static String prepareProductName(String[] args) {
StringBuilder builder = new StringBuilder();
for (int i = 1; i < args.length - 2; i++) {
builder.append(args[i]);
}
String productName = builder.toString().trim();
if (productName.length() < 30) {
StringBuilder st = new StringBuilder();
st.append(productName);
for (int i = productName.length(); i < 30; i++) {
st.append(" ");
}
productName = st.toString();
}
else if (productName.length() > 30) {
StringBuilder st = new StringBuilder();
char[] ch = productName.toCharArray();
for (int i = 0; i < 30; i++) {
st.append(Character.toString(ch[i]));
}
productName = st.toString();
}
return productName.substring(0, 30);
}
private static String prepareAmmount(String[] args) {
String amount = args[args.length - 1];
if (amount.length() < 4) {
StringBuilder st = new StringBuilder();
st.append(amount);
for (int i = amount.length(); i < 4; i++) {
st.append(" ");
}
amount = st.toString();
}
else if (amount.length() > 4) {
StringBuilder st = new StringBuilder();
char[] ch = amount.toCharArray();
for (int i = amount.length() - 4; i < amount.length(); i++) {
st.append(Character.toString(ch[i]));
}
amount = st.toString();
}
return amount.substring(0, 4);
}
private static String preparePrice(String[] args) {
String price = args[args.length - 2];
if (price.length() < 8) {
StringBuilder st = new StringBuilder();
st.append(price);
for (int i = price.length(); i < 8; i++) {
st.append(" ");
}
price = st.toString();
}
else if (price.length() > 8) {
StringBuilder st = new StringBuilder();
char[] ch = price.toCharArray();
for (int i = 0; i < 8; i++) {
st.append(Character.toString(ch[i]));
}
price = st.toString();
}
return price.substring(0, 8);
}
}
*/
import java.io.*;
import java.util.Locale;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fname = reader.readLine();
if (args.length > 0)
if (args[0].equals("-c"))
add(args, fname);
reader.close();
}
public static int getLastId(String fname) throws FileNotFoundException {
Scanner file = new Scanner(new File(fname));
int maxId = Integer.MIN_VALUE;
while (file.hasNextLine())
{
String line = file.nextLine();
int id = Integer.parseInt(line.substring(0, 8).trim());
if (id > maxId)
maxId = id;
}
file.close();
return maxId;
}
public static void add(String[] args, String fname) throws IOException {
if (args.length < 4)
return;
FileWriter file = new FileWriter(fname, true);
String id = String.format("%-8.8s", getLastId(fname) + 1);
String productName = String.format("%-30.30s", getProductNameInArgs(args));
String price = String.format("%-8.8s", String.format(Locale.US, "%.2f", Double.parseDouble(args[args.length-2])));
String quantity = String.format("%-4.4s", args[args.length-1]);
file.write(System.getProperty( "line.separator" ));
file.write(id + productName + price + quantity);
file.close();
}
public static String getProductNameInArgs(String[] args) {
StringBuilder productName = new StringBuilder();
for (int i = 1; i < args.length - 2; i++) {
productName.append(args[i]+" ");
}
return productName.toString();
}
}
Leave A Comment