0

Это моя программа написанная на Java.. Простая АЗС станция.. Есть номер колонки.. номер пистолета.. цена.. литраж.. Я новичок в программировании, учусь так сказать. Вот решил спросить что можно улучшить.

import java.util.Scanner;

public class AZS {
    public static void main(String[] args) throws Exception {
        Numkoll mn = new Numkoll();
        mn.numkoll();
        mn.inputkol();

        int Zerro = 0;
        int One = 1;
        int two = 2;
        int Three = 3;
        int Four = 4;
        int Five = 5;
        int n = mn.numkol;
        int c1;

        if (n >= 0) {
            c1 = n % 10;
            if (c1 == Zerro) {
                Exit ex = new Exit();
                ex.output();
                System.exit(0);
            }

        } // Вихід

        if (n > 0) {
            c1 = n % 10;
            if (c1 == One) {

                AZS_1 docOne = new AZS_1();
                docOne.input();
                docOne.isRingRoute();
                docOne.output();
            }
        } // Kolonka #1
        if (n > 0) {
            c1 = n % 10;
            if (c1 == two) {
                AZS_2 docTwo = new AZS_2();
                docTwo.input();
                docTwo.isRingRoute();
                docTwo.output();
            }
        } // Kolonka #2
        if (n > 0) {
            c1 = n % 10;
            if (c1 == Three){
                AZS_3 docThree = new AZS_3();
                docThree.input();
                docThree.isRingRoute();
                docThree.output();
            }
        } // Kolonka #3
        if (n > 0) {
            c1 = n % 10;
            if (c1 == Four){
                AZS_4 docFour = new AZS_4();
                docFour.input();
                docFour.isRingRoute();
                docFour.output();
            }
        } // Kolonka #4
        if (n > 0) {
            c1 = n % 10;
            if (c1 == Five){
                AZS_5 docFive = new AZS_5();
                docFive.input();
                docFive.isRingRoute();
                docFive.output();
            }
        } // Kolonka #5
    }  ////// all заправки. START!

    public static class Numkoll{
        private  int numkol;

        public void numkoll() {
            this.numkol = 0;
        }

        public void inputkol() {

            Scanner in = new Scanner(System.in);
            System.out.println("Доброго часу доби");
            System.out.printf("Оберіть номер колонки (1-5)(0 - Вихід): ");numkol = in.nextInt();
        }
    }

    public  static class Exit{
        public void output(){
            System.out.println("На все добре!");
        }
    }

    public static class AZS_1 {
        private int NumberPistol;
        private double Kilkist;

        public AZS_1() {
            this.NumberPistol = 0;
            this.Kilkist = 0;
        } //throws Exception

        public void input() { //ввід з Клави
            Scanner in = new Scanner(System.in);

            System.out.println("1) A-76 | 19,32 грн.");
            System.out.println("2) A-80 | 19,76 Грн.");
            System.out.printf("Номер пістолета 1 або 2: ");this.NumberPistol = in.nextInt();
            System.out.printf("Кількість L: ");this.Kilkist = in.nextDouble(); System.out.println("");
            System.out.printf("Зачекайте. Ваш запит виконується.  "); System.out.println("");

            in.close();
        }

        public void output() throws Exception { // вивід на екран

            int n = this.NumberPistol;
            int c1;
            int a = 1;
            int b = 2;

            if(n > 0){
                c1 = n %10;
                if (c1 == a){
                    int i = a;
                    System.out.println("Номер пістолета: " + i );
                    System.out.println("Кількість L: " + this.Kilkist);
                    System.out.println("Час на заправку автомобіля: Очікуйте 100 % ");

                    String anim = "|/-\\ ";
                    for (int x = 0; x < 101; x++) {
                        String data = "\r" + anim.charAt(x % anim.length()) + x + " %";
                        System.out.write(data.getBytes());
                        Thread.sleep((long) (this.Kilkist / 0.05));// millisec = 0.5 L| SEc
                    }
                }

                if (c1 == b){
                    int e = b;
                    System.out.println("Номер пістолета: " + e );
                    System.out.println("Кількість L: " + this.Kilkist);
                    System.out.println("Час на заправку автомобіля: Очікуйте 100 % ");

                    String anim = "|/-\\";
                    for (int x = 0; x < 101; x++) {
                        String data = "\r" + anim.charAt(x % anim.length()) + x + " %";
                        System.out.write(data.getBytes());
                        Thread.sleep((long) (this.Kilkist / 0.05));// millisec = 0.5 L| SEc
                    }
                }
            }
        }

        public void isRingRoute() { //розрахунок ціна кількість
            int a = 1;
            int b = 2;
            int c1;
            int n = this.NumberPistol;

            if (n > 0) {
                c1 = n % 10;

                if (c1 == a) {
                    double i = this.Kilkist * 19.32; // Ціна А76 19,32
                    System.out.println("Сумма до сплати: " + i);
                }
                if (c1 == b) {
                    double e = this.Kilkist * 19.76; // Ціна А80 19,76
                    System.out.println("Сумма до сплати : " + e);
                }
            }
        }
        ////////////////////////////////////////////////////////////
    } /////////////////////////////////   Колонка №1

    public static class AZS_2 {

        private int NumberPistol;
        private double Kilkist;

        public AZS_2() {
            this.NumberPistol = 0;
            this.Kilkist = 0;
        } //throws Exception

        public void input() { //ввід з Клави
            Scanner in = new Scanner(System.in);

            System.out.println("1) A-92 | 25.39 грн.");
            System.out.println("2) A-95 | 26.40 Грн.");
            System.out.printf("Номер пістолета 1 або 2: ");this.NumberPistol = in.nextInt();
            System.out.printf("Кількість L: ");this.Kilkist = in.nextDouble(); System.out.println("");
            System.out.printf("Зачекайте. Ваш запит виконується.  "); System.out.println("");

            in.close();
        }

        public void output() throws Exception { // вивід на екран
            int n = this.NumberPistol;
            int c1;
            int a = 1;
            int b = 2;

            if(n > 0){
                c1 = n %10;
                if (c1 == a){
                    int i = a;
                    System.out.println("Номер пістолета: " + i );
                    System.out.println("Кількість L: " + this.Kilkist);
                    System.out.println("Час на заправку автомобіля: Очікуйте 100 % ");

                    String anim = "|/-\\ ";
                    for (int x = 0; x < 101; x++) {
                        String data = "\r" + anim.charAt(x % anim.length()) + x + " %";
                        System.out.write(data.getBytes());
                        Thread.sleep((long) (this.Kilkist / 0.05));// millisec = 0.5 L| SEc
                    }
                }

                if (c1 == b){
                    int e = b;
                    System.out.println("Номер пістолета: " + e );
                    System.out.println("Кількість L: " + this.Kilkist);
                    System.out.println("Час на заправку автомобіля: Очікуйте 100 % ");

                    String anim = "|/-\\";
                    for (int x = 0; x < 101; x++) {
                        String data = "\r" + anim.charAt(x % anim.length()) + x + " %";
                        System.out.write(data.getBytes());
                        Thread.sleep((long) (this.Kilkist / 0.05));// millisec = 0.5 L| SEc
                    }
                }
            }
        }

        public void isRingRoute() { //розрахунок ціна кількість
            int a = 1;
            int b = 2;
            int c1;
            int n = this.NumberPistol;

            if (n > 0) {
                c1 = n % 10;

                if (c1 == a) {
                    double i = this.Kilkist * 25.39; // Ціна А92 25.39
                    System.out.println("Сумма до сплати: " + i);
                }
                if (c1 == b) {
                    double e = this.Kilkist * 26.40; // Ціна А95 26.40
                    System.out.println("Сумма до сплати: " + e);
                }
            }
        }
        ////////////////////////////////////////////////////////////
    } /////////////////////////////////   Колонка №2

    public static class AZS_3 {
        private int NumberPistol;
        private double Kilkist;

        public AZS_3() {
            this.NumberPistol = 0;
            this.Kilkist = 0;
        } //throws Exception


        public void input() { //ввід з Клави
            Scanner in = new Scanner(System.in);

            System.out.println("1) A-95 Premium | 27.58 грн.");
            System.out.println("2) А-98 | 27.99 Грн.");
            System.out.printf("Номер пістолета 1 або 2: ");this.NumberPistol = in.nextInt();
            System.out.printf("Кількість L: ");this.Kilkist = in.nextDouble(); System.out.println("");
            System.out.printf("Зачекайте. Ваш запит виконується.  "); System.out.println("");

            in.close();
        }

        public void output() throws Exception { // вивід на екран
            int n = this.NumberPistol;
            int c1;
            int a = 1;
            int b = 2;

            if(n > 0){
                c1 = n %10;
                if (c1 == a){
                    int i = a;
                    System.out.println("Номер пістолета: " + i );
                    System.out.println("Кількість L: " + this.Kilkist);
                    System.out.println("Час на заправку автомобіля: Очікуйте 100 % ");

                    String anim = "|/-\\ ";
                    for (int x = 0; x < 101; x++) {
                        String data = "\r" + anim.charAt(x % anim.length()) + x + " %";
                        System.out.write(data.getBytes());
                        Thread.sleep((long) (this.Kilkist / 0.05));// millisec = 0.5 L| SEc
                    }
                }

                if (c1 == b){
                    int e = b;
                    System.out.println("Номер пістолета: " + e );
                    System.out.println("Кількість L: " + this.Kilkist);
                    System.out.println("Час на заправку автомобіля: Очікуйте 100 % ");

                    String anim = "|/-\\";
                    for (int x = 0; x < 101; x++) {
                        String data = "\r" + anim.charAt(x % anim.length()) + x + " %";
                        System.out.write(data.getBytes());
                        Thread.sleep((long) (this.Kilkist / 0.05));// millisec = 0.5 L| SEc
                    }
                }
            }
        }

        public void isRingRoute() { //розрахунок ціна кількість
            int a = 1;
            int b = 2;
            int c1;
            int n = this.NumberPistol;

            if (n > 0) {
                c1 = n % 10;

                if (c1 == a) {
                    double i = this.Kilkist * 27.58; // Ціна А95 27.58
                    System.out.println("Сумма до сплати: " + i);
                }
                if (c1 == b) {
                    double e = this.Kilkist * 27.99; // Ціна А98 27.99
                    System.out.println("Сумма до сплати: " + e);
                }
            }
        }
        ////////////////////////////////////////////////////////////
    } /////////////////////////////////   Колонка №3

    public static class AZS_4 {
        private int NumberPistol;
        private double Kilkist;

        public AZS_4() {
            this.NumberPistol = 0;
            this.Kilkist = 0;
        } //throws Exception


        public void input() { //ввід з Клави
            Scanner in = new Scanner(System.in);

            System.out.println("1) А-100 Mustang | 27,99 грн.");
            System.out.println("2) Euro 5 | 23,23 Грн.");
            System.out.printf("Номер пістолета 1 або 2: ");this.NumberPistol = in.nextInt();
            System.out.printf("Кількість L: ");this.Kilkist = in.nextDouble(); System.out.println("");
            System.out.printf("Зачекайте. Ваш запит виконується.  "); System.out.println("");

            in.close();
        }

        public void output() throws Exception { // вивід на екран
            int n = this.NumberPistol;
            int c1;
            int a = 1;
            int b = 2;

            if(n > 0){
                c1 = n %10;
                if (c1 == a){
                    int i = a;
                    System.out.println("Номер пістолета: " + i );
                    System.out.println("Кількість L: " + this.Kilkist);
                    System.out.println("Час на заправку автомобіля: Очікуйте 100 % ");

                    String anim = "|/-\\ ";
                    for (int x = 0; x < 101; x++) {
                        String data = "\r" + anim.charAt(x % anim.length()) + x + " %";
                        System.out.write(data.getBytes());
                        Thread.sleep((long) (this.Kilkist / 0.05));// millisec = 0.5 L| SEc
                    }
                }

                if (c1 == b){
                    int e = b;
                    System.out.println("Номер пістолета: " + e );
                    System.out.println("Кількість L: " + this.Kilkist);
                    System.out.println("Час на заправку автомобіля: Очікуйте 100 % ");

                    String anim = "|/-\\";
                    for (int x = 0; x < 101; x++) {
                        String data = "\r" + anim.charAt(x % anim.length()) + x + " %";
                        System.out.write(data.getBytes());
                        Thread.sleep((long) (this.Kilkist / 0.05));// millisec = 0.5 L| SEc
                    }
                }
            }
        }

        public void isRingRoute() { //розрахунок ціна кількість
            int a = 1;
            int b = 2;
            int c1;
            int n = this.NumberPistol;

            if (n > 0) {
                c1 = n % 10;

                if (c1 == a) {
                    double i = this.Kilkist * 19.32; // Ціна А76 19,32
                    System.out.println("Сумма до сплати: " + i);
                }
                if (c1 == b) {
                    double e = this.Kilkist * 23.23; // Ціна Euro 5 23.23
                    System.out.println("Сумма до сплати: " + e);
                }
            }
        }
        ////////////////////////////////////////////////////////////
    } /////////////////////////////////   Колонка №4

    public static class AZS_5 {
        private int NumberPistol;
        private double Kilkist;

        public AZS_5() {
            this.NumberPistol = 0;
            this.Kilkist = 0;
        } //throws Exception

        public void input() { //ввід з Клави
            Scanner in = new Scanner(System.in);

            System.out.println("1) ДП | 25,77 грн.");
            System.out.println("2) ГаЗ | 10,95 Грн.");
            System.out.printf("Номер пістолета 1 або 2: ");this.NumberPistol = in.nextInt();
            System.out.printf("Кількість L: ");this.Kilkist = in.nextDouble(); System.out.println("");
            System.out.printf("Зачекайте. Ваш запит виконується.  "); System.out.println("");

            in.close();
        }

        public void output() throws Exception { // вивід на екран
            int n = this.NumberPistol;
            int c1;
            int a = 1;
            int b = 2;

            if(n > 0){
                c1 = n %10;
                if (c1 == a){
                    int i = a;
                    System.out.println("Номер пістолета: " + i );
                    System.out.println("Кількість L: " + this.Kilkist);
                    System.out.println("Час на заправку автомобіля: Очікуйте 100 % ");

                    String anim = "|/-\\ ";
                    for (int x = 0; x < 101; x++) {
                        String data = "\r" + anim.charAt(x % anim.length()) + x + " %";
                        System.out.write(data.getBytes());
                        Thread.sleep((long) (this.Kilkist / 0.05));// millisec = 0.5 L| SEc
                    }
                }

                if (c1 == b){
                    int e = b;
                    System.out.println("Номер пістолета: " + e );
                    System.out.println("Кількість L: " + this.Kilkist);
                    System.out.println("Час на заправку автомобіля: Очікуйте 100 % ");

                    String anim = "|/-\\";
                    for (int x = 0; x < 101; x++) {
                        String data = "\r" + anim.charAt(x % anim.length()) + x + " %";
                        System.out.write(data.getBytes());
                        Thread.sleep((long) (this.Kilkist / 0.05));// millisec = 0.5 L| SEc
                    }
                }
            }
        }

        public void isRingRoute() { //розрахунок ціна кількість
            int a = 1;
            int b = 2;
            int c1;
            int n = this.NumberPistol;

            if (n > 0) {
                c1 = n % 10;

                if (c1 == a) {
                    double i = this.Kilkist * 25.77; // Ціна ДП 25,77
                    System.out.println("Сумма до сплати: " + i);
                }
                if (c1 == b) {
                    double e = this.Kilkist * 10.95; // Ціна ГаЗ 10,95
                    System.out.println("Сумма до сплати: " + e);
                }
            }
        }
        ////////////////////////////////////////////////////////////
    } /////////////////////////////////   Колонка №5
}
11
  • 3
    Ты сейчас серьезно?... Даешь код больше 100 строк кода и говоришь: сделайте его лучше. Тебе на фриланс, братан
    – Lofectr
    20 сен 2020 в 16:22
  • Вижу много одного и того же кода, который не переиспользуется никак. Ваш код можно и нужно улучшить!
    – MoloF
    20 сен 2020 в 16:24
  • Я не прошу сделать его лучше.. просто как можно улучшить... по другому написать...сократить что то.. может? 20 сен 2020 в 16:24
  • Какие учебники новичком в программировании прочитаны? 20 сен 2020 в 16:25
  • 1
    для начала уберите дублирующий код. все классы азс ничем не отличаются, кроме вида топлива и цены. посему это должны быть не разные классы, а экземпляры одного класса. как исправите - меняйте код в вопросе и пойдем дальше 20 сен 2020 в 16:31

1 ответ 1

0

Для начала давайте вы разберете тот код, который я выложил ниже, потому как ваш код за гранью добра и зла, а уже потом приступите к рефакторингу:

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.stream.Collectors;
import java.util.*;

public class AZS {
    public static void main(String[] args) throws Exception {        
        GasStationFactory gasStationFactory = new GasStationFactory ();
        Scanner in = new Scanner(System.in);
        System.out.println("Доброго часу доби");
        System.out.println("Оберіть номер колонки (1-"+gasStationFactory.getStationNumber()+") інше - Вихід): ");
        gasStationFactory.of(in.nextLine()).ifPresent(gasStation -> gasStation.start());
        System.out.println("На все добре!");
    }
}

class GasStationFactory{
    
    private final List<GasStation> gasStations;
    
    public GasStationFactory (){
        gasStations = new ArrayList<>();
        gasStations.add(new GasStation(new Fuel("A-76", 1932L), new Fuel("A-80", 1976L)));        
        gasStations.add(new GasStation(new Fuel("A-92", 2539L), new Fuel("A-95", 2640L)));        
        gasStations.add(new GasStation(new Fuel("A-95 Premium", 2758L), new Fuel("A-98", 2799L)));        
        gasStations.add(new GasStation(new Fuel("А-100 Mustang", 2799L), new Fuel("Euro 5", 2323L)));        
        gasStations.add(new GasStation(new Fuel("ДП", 2577L), new Fuel("ГаЗ", 1095L)));
    }
    
    public int getStationNumber() {
        return gasStations.size();
    }
    
    public Optional<GasStation> of(String gasStationNumber) {
        try {
            return Optional.of(gasStations.get(Integer.valueOf(gasStationNumber) - 1));
        } catch (NumberFormatException | IndexOutOfBoundsException e) {
            return Optional.empty();
        }
    }
    
}

class GasStation {

    private final static String ANIM = "|/-\\ ";

    private int pistolNumber;
    private double fuelLiter;

    private final List<Fuel> fuels;

    public GasStation(Fuel... fuels) {
        this.fuels = Arrays.stream(fuels).collect(Collectors.toList());
    }
    
    public boolean start() {
        try {
            input();
            output();
            return true;
        } catch (NumberFormatException | IndexOutOfBoundsException | IOException e) {
            return false;
        } catch (InterruptedException ex) {
            throw new RuntimeException(ex);
        }
    }

    private void input() {
        Scanner in = new Scanner(System.in);
        for (int i = 0; i < fuels.size(); i++) 
            System.out.println((i + 1) + ") " + fuels.get(i));
        System.out.println("Номер пістолета: ");
        pistolNumber = Integer.valueOf(in.nextLine());
        fuels.get(pistolNumber - 1);
        System.out.println("Кількість(л): ");
        fuelLiter = Double.valueOf(in.nextLine());
        System.out.printf("\r\nЗачекайте. Ваш запит виконується.\r\n");
    }

    private void output() throws IOException, InterruptedException {
        System.out.println("Номер пістолета: " + pistolNumber);
        System.out.println("Кількість(л): " + fuelLiter);
        System.out.println("Час на заправку автомобіля: Очікуйте 100 % ");
        for (int i = 0; i < 101; i++) {
            System.out.write(("\r" + ANIM.charAt(i % ANIM.length()) + i + " %").getBytes());
            Thread.sleep((long) (this.fuelLiter / 0.05));// millisec = 0.5 L| SEc
        }
        System.out.println(fuels.get(pistolNumber - 1).totalCost(fuelLiter));
    } 
}

class Fuel {
    
    private final static DecimalFormat FORMATTER = new DecimalFormat("###.##");

    private final long cost;
    private final String name;
    
    public Fuel(String name, long cost) {
        this.name = name;
        this.cost = cost;        
    }

    public long getCost() {
        return cost;
    }

    public String getName() {
        return name;
    }
    
    public String totalCost(double fuelLiter) {
        return "Сумма до сплати: " + FORMATTER.format(fuelLiter*cost) + " грн.";
    }
    
    @Override
    public String toString() {
        return name + " | " + FORMATTER.format(cost/100d) + " грн.";
    }
    
}
1

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.