Foros aprenderaprogramar.com

Aprender a programar => Aprender a programar desde cero => Mensaje iniciado por: CoduJ en 03 de Agosto 2020, 21:30

Título: Cómo se hace programación orientada a objetos retroalimentación código calidad
Publicado por: CoduJ en 03 de Agosto 2020, 21:30
Buenas, espero que se encuentren bien. Otro hilo en donde expongo mi código buscando recibir una retroalimentación; he estado aprendiendo la POO de Java y demás, pero quise probar con las funciones, para eso, programé un programa para hacer compras, similar a un proyecto que había hecho, pero en este caso quería mejorarlo.


Código: [Seleccionar]
import java.util.Scanner;
import java.util.Random;

public class Test_12{
   static Scanner Input = new Scanner(System.in);
   static Random DineroR = new Random();   
   static byte opc = 0; //toma de decisiones SI/NO
   static int indiceProducto = 0, cantidadProductos = 0, productoCosto = 0, dinero = 10, dineroAux = 0, dineroExtra = 0;
   static boolean estadoCompra = false;
   public static void main(String[] args){
      int cantidadProductos = 0;
      byte opc = 0;
      boolean estadoTienda = true;
      while(estadoTienda == true){
         dineroAux = dinero;
         estadoCompra = true;
         System.out.println("\t--- TIENDA ---\nSeleccione categoria: 1: Comida | 2: Herramientas | 3: Decoraciones | 4: Mostrar dinero | 5: Sacar dinero | 6: Salir");
         opc = (byte) Integer.parseInt(Input.next());
         while(opc < 1 || opc > 6){ //error al insertar datos
            System.out.println("No ha seleccionado de manera correcta. . .");
            System.out.println("\t--- TIENDA ---\nSeleccione categoria: 1: Comida | 2: Herramientas | 3: Decoraciones | 4: Mostrar dinero | 5: Sacar dinero | 6: Salir");
            opc = (byte) Integer.parseInt(Input.next());
         }
         switch(opc){ //menu
            case 1: //comida
               Comida();
            break;
            case 2: //herramienatas
               Herramientas();
            break;           
            case 3: //decoraciones
               Decoraciones();
            break;
            case 4: //mostrar dinero
               System.out.println("Dinero: $" + dinero);
            break;
            case 5:
               dineroExtra = DineroR.nextInt(1000) + 1;
               dinero += dineroExtra;
               System.out.println("Has recibido " + "$" + dineroExtra);
            break;
            case 6: //salir
               estadoTienda = false;
               System.out.println("Usted ha salido de la tienda. . .");
            break;
         }
      }
   }

   public static void Comida(){ //menu opcion 1
      int costo[] = {5, 15, 20};
      String comida[] = {"Papas", "Manzanas", "Pollo"};
      while(estadoCompra == true){
         for(int i = 0; i < comida.length; i++){ //imprimir comidas
            System.out.println("Comida N°"+ (i+1) + ": " + comida[i] + " | " + "$" + costo[i]);
         }
         System.out.print("\tEscriba lo que desea llevar segun el numero del producto\nLLevar: "); //seleccionar producto
         indiceProducto = (byte) Integer.parseInt(Input.next());         
         while(indiceProducto < 1 || indiceProducto > 3){ //error al insertar datos
            System.out.println("\t\tNo ha seleccionado de manera correcta. . .");
            for(int i = 0; i < comida.length; i++){ //imprimir comidas
               System.out.println("Comida N°"+ (i+1) + ": " + comida[i] + " | " + "$" + costo[i]);
            }
            System.out.print("\tEscriba lo que desea llevar segun el numero del producto\nLLevar: ");
            indiceProducto = (byte) Integer.parseInt(Input.next());           
         }
         productoCosto = costo[indiceProducto-1];
         indiceProducto--;
         System.out.print("Cuanto desea llevar: "); //cantidad de producto
         cantidadProductos = Integer.parseInt(Input.next());
         while(cantidadProductos < 1){ //error al insertar datos a la cantidad de productos
            System.out.println("No puede llevar " + cantidadProductos + " de " + comida[indiceProducto]);
            System.out.print("Cuanto desea llevar: ");
            cantidadProductos = Integer.parseInt(Input.next());
         }
         productoCosto *= cantidadProductos;
         dineroAux -= productoCosto;
         if(dineroAux < productoCosto){ //operacion de cantidad de productos y restar dinero
            System.out.println("\tNo queda suficiente dinero\n\t\tVuelva mas tarde");
            break;
         }else{
            dinero -= productoCosto;
         }
         System.out.println("Salir: 1: SI | 2: NO"); //salir
         opc = (byte) Integer.parseInt(Input.next());
         while(opc < 1 || opc > 2){ //error opciones SI o NO de salir del bucle
            System.out.println("\t\tNo ha seleccionado de manera correcta. . .");
            System.out.println("Salir: 1: SI | 2: NO");
            opc = (byte) Integer.parseInt(Input.next());
         }
         if(opc == 1){ //aceptar salir del bucle
            estadoCompra = false;
         }
      }
   }
   public static void Herramientas(){ //menu opcion 2
      int costo[] = {25, 40, 80};
      String herramientas[] = {"Martillo", "Destornillador", "Sierra"};
      while(estadoCompra == true){
         for(int i = 0; i < herramientas.length; i++){ //imprimir herramientas
            System.out.println("Herramienta N°" + (i+1) + ": " + herramientas[i] + " | " + "$" + costo[i]);
         }
         System.out.print("\tEscriba lo que desea llevar segun el numero del producto\nLLevar: "); //seleccionar producto
         indiceProducto = (byte) Integer.parseInt(Input.next());         
         while(indiceProducto < 1 || indiceProducto > 3){ //error al insertar datos
            System.out.println("\t\tNo ha seleccionado de manera correcta. . .");
            for(int i = 0; i < herramientas.length; i++){ //imprimir herramientas
               System.out.println("Herramienta N°" + (i+1) + ": " + herramientas[i] + " | " + "$" + costo[i]);
            }
            System.out.print("\tEscriba lo que desea llevar segun el numero del producto\nLLevar: ");
            indiceProducto = (byte) Integer.parseInt(Input.next());           
         }
         productoCosto = costo[indiceProducto-1];
         indiceProducto--;
         System.out.print("Cuanto desea llevar: "); //cantidad de producto
         cantidadProductos = Integer.parseInt(Input.next());
         while(cantidadProductos < 1){ //error al insertar datos a la cantidad de productos
            System.out.println("No puede llevar " + cantidadProductos + " de " + herramientas[indiceProducto]);
            System.out.print("Cuanto desea llevar: ");
            cantidadProductos = Integer.parseInt(Input.next());
         }
         productoCosto *= cantidadProductos;
         dineroAux -= productoCosto;
         if(dineroAux < productoCosto){ //operacion de cantidad de productos y restar dinero
            System.out.println("\tNo queda suficiente dinero\n\t\tVuelva mas tarde");
            break;
         }else{
            dinero -= productoCosto;
         }
         System.out.println("Salir: 1: SI | 2: NO"); //salir
         opc = (byte) Integer.parseInt(Input.next());
         while(opc < 1 || opc > 2){ //error opciones SI o NO de salir del bucle
            System.out.println("\t\tNo ha seleccionado de manera correcta. . .");
            System.out.println("Salir: 1: SI | 2: NO");
            opc = (byte) Integer.parseInt(Input.next());
         }
         if(opc == 1){ //aceptar salir del bucle
            estadoCompra = false;
         }
      }
   }
   public static void Decoraciones(){ //menu opcion 3
      int costo[] = {4, 20, 30};
      String decoraciones[] = {"Jarron", "Mueble", "Planta de plastico"};     
      while(estadoCompra == true){
         for(int i = 0; i < decoraciones.length; i++){ //imprimir decoraciones
            System.out.println("Decoracion N°" + (i+1) + ": " + decoraciones[i] + " | " + "$" + costo[i]);
         }
         System.out.print("\tEscriba lo que desea llevar segun el numero del producto\nLLevar: "); //seleccionar producto
         indiceProducto = (byte) Integer.parseInt(Input.next());         
         while(indiceProducto < 1 || indiceProducto > 3){ //error al insertar datos
            System.out.println("\t\tNo ha seleccionado de manera correcta. . .");
            for(int i = 0; i < decoraciones.length; i++){ //imprimir decoraciones
               System.out.println("Decoracion N°" + (i+1) + ": " + decoraciones[i] + " | " + "$" + costo[i]);
            }
            System.out.print("\tEscriba lo que desea llevar segun el numero del producto\nLLevar: ");
            indiceProducto = (byte) Integer.parseInt(Input.next());           
         }
         productoCosto = costo[indiceProducto-1];
         indiceProducto--;
         System.out.print("Cuanto desea llevar: "); //cantidad de producto
         cantidadProductos = Integer.parseInt(Input.next());
         while(cantidadProductos < 1){ //error al insertar datos a la cantidad de productos
            System.out.println("No puede llevar " + cantidadProductos + " de " + decoraciones[indiceProducto]);
            System.out.print("Cuanto desea llevar: ");
            cantidadProductos = Integer.parseInt(Input.next());
         }
         productoCosto *= cantidadProductos;
         dineroAux -= productoCosto;
         if(dineroAux < productoCosto){ //operacion de cantidad de productos y restar dinero
            System.out.println("\tNo queda suficiente dinero\n\t\tVuelva mas tarde");
            break;
         }else{
            dinero -= productoCosto;
         }
         System.out.println("Salir: 1: SI | 2: NO"); //salir
         opc = (byte) Integer.parseInt(Input.next());
         while(opc < 1 || opc > 2){ //error opciones SI o NO de salir del bucle
            System.out.println("\t\tNo ha seleccionado de manera correcta. . .");
            System.out.println("Salir: 1: SI | 2: NO");
            opc = (byte) Integer.parseInt(Input.next());
         }
         if(opc == 1){ //aceptar salir del bucle
            estadoCompra = false;
         }
      }
   }
}
Título: Re:Java - Opinión sobre código
Publicado por: Kabuto en 04 de Agosto 2020, 01:32
Hola, un detallito.
La clase Byte también te permite parsear (https://docs.oracle.com/javase/7/docs/api/java/lang/Byte.html#parseByte(java.lang.String)) un String.

Así que estos parseos a Integer + casteos a byte:

Código: [Seleccionar]
opc = (byte) Integer.parseInt(Input.next());
Los puedes hacer directamente así:
Código: [Seleccionar]
opc = Byte.parseByte(Input.next());

Y otra cosa, dices que has estado aprendiendo POO..., pues este habría sido un ejercicio interesante para aplicarlo: una clase Producto, tal vez unas clases Comida, Decoracion, Herramienta que hereden de Producto..., quizás una clase Compra que reciba Productos y calcule el importe final...

Hay posibilidades para practicar POO