Compare elements of an array to find the greatest

3

In the following code I need to enter two car identifiers per Scanner and show me which is the car that has traveled the most kilometers.

How could it be done?

import java.util.Scanner;
public class Pruebas {
    public static void main(String[] args) {
        Scanner teclado = new Scanner(System.in);
        Coches coche = new Coches();
        // Se almacenan un numero máximo de coches (4), una vez introducidos 4 coches avisa al usuario de que no se pueden agregar más coches.
        Coches array [] = new Coches [4];
        int contador = 0;
        if (contador < array.length) {         
            System.out.println("Introduce el identificador del coche : ");          
            int identificador;
            int kilometros;
            System.out.print("Identificador :");
            identificador = teclado.nextInt();          
            System.out.print("Kilometros :");
            kilometros = teclado.nextInt();
            coche = new Coches(identificador,kilometros);         
            array [contador] = coche;
            contador++;     
            System.out.print("Coche dado de alta");
            System.out.println();
        }else{         
            System.out.print("Se ha alcanzado el maximo de coches");
        }
        // Comparar coches: el usuario introducirá dos identificadores de coches y se mostrará el coche que haya recorrido más kilometros.

//EDIT

// Comparar dos coches introduciendo sus identificadores.

System.out.print("Introduzca el primer identificador :");
System.out.print("Introduzca el segundo identificador :");

    }
}
    
asked by InThaHouse 12.01.2018 в 21:00
source

3 answers

0

To capture the data of Coches by Scanner and add them to your array you must use while , since currently you can only create only one instance of Car.

Regarding your class Cars you can add methods to obtain the properties like the identifier and the kilometers, to make comparison of kilometer with the other elements.

public class Coches {

  int identificador;
  int kilometros;

  public Coches(){}

  public Coches(int identificador, int kilometros) {
    this.identificador = identificador;
    this.kilometros = kilometros;
  }

  public int getIdentificador(){
     return identificador;
  }

   public int getKilometros(){
     return kilometros;
  }


}

In this way you can make a comparison of your kilometers and determine which is the best mileage, this would be an example based on your original code:

  public class Pruebas{

     public static void main(String[] args) {

            Scanner teclado = new Scanner(System.in);

            Coches coche = new Coches();

            // Se almacenan un numero máximo de coches (4).

            Coches array [] = new Coches [4];

            int contador = 0;

            //if (contador < array.length) {
            while (contador < array.length) {

                System.out.println("Introduce el identificador del coche : ");

                int identificador;
                int kilometros;

                System.out.print("Identificador :");
                identificador = teclado.nextInt();

                System.out.print("Kilometros :");
                kilometros = teclado.nextInt();

                coche = new Coches(identificador,kilometros);

                array [contador] = coche;
                contador++;

                System.out.print("Coche dado de alta");
                System.out.println();

            }


                System.out.print("Se ha alcanzado el maximo de coches.\n");

                  //Busca cual realizo mayor kilometraje:

                  int maxKilometros = 0;
                  int indiceCoche = 0;
                  for(int i = 0; i< array.length; i++){                  
                      if(array[i].getKilometros()>maxKilometros){
                          maxKilometros = array[i].getKilometros();
                          indiceCoche = i;
                      }                   
                  }

                  System.out.print("El coche que ha recorrido más kilometros es:"  + array[indiceCoche].getIdentificador() + " Kilometros: "+ array[indiceCoche].getKilometros() +"\n");

        }
    }

Example:

Introduce el identificador del coche : 
Identificador :1
Kilometros :200
Coche dado de alta
Introduce el identificador del coche : 
Identificador :2
Kilometros :256
Coche dado de alta
Introduce el identificador del coche : 
Identificador :3
Kilometros :280
Coche dado de alta
Introduce el identificador del coche : 
Identificador :4
Kilometros :120
Coche dado de alta
Se ha alcanzado el maximo de coches
El coche que ha recorrido más kilometros es:3 Kilometros: 280
    
answered by 12.01.2018 / 21:25
source
1

First a suggestion, do not define a class in plural Coches coche = new Coches(); but in singular Coche coche = new Coche();

and the way to do it is to go through the arrangement of cars and take the kilometers of each car and compare them:

    Coche cocheGanador;//objeto para el cohce que tenga  más kilometros
    int kilometrosCoche=0;//auxiliar de los kilometros

    for(Coche c:array){//se recorre el array de los coche para comparar
        if(c.kilometros>kilometrosCoche){//Si la variable auxiliar es menor que la del coche actual
            cocheGanador=c;//ahora el coche ganador es el cohe actual
            kilometrosCoche=c.kilometros;//lo kilometros a superar aahora son los del coche actual
        }
    }
    
answered by 12.01.2018 в 21:17
1

There are some details in your code that you should keep in mind.

First of all you should create e instanciar the object Coches within ciclo (while) , this last one does not have it therefore as it is your code will only be entered a car at array .

I should have everything in a while maybe. Also by convention the name of the classes are written in Singular. Coche To compare and find the largest there are several ways. in this answer I added some , of course you must modify with the field you want to compare.

Scanner teclado = new Scanner(System.in);
// Se almacenan un numero máximo de coches (4).
Coches array [] = new Coches [4];
int contador=0,identificador,kilometros;

while (contador < array.length) { // Controlamos que no sea mayor a 4

    System.out.println("Introduce el identificador del coche : ");
    System.out.print("Identificador :");
    identificador = teclado.nextInt();
    System.out.print("Kilometros :");
    kilometros = teclado.nextInt();
    //Crear Dentro
    Coches coche = new Coches(identificador,kilometros);
    array [contador] = coche;
    contador++;
    System.out.print("Coche dado de alta");
    System.out.println();
}


Coches co = new Coches();
for (Coches coche: array) 
     if(coche.getKilometros()>co.getKilometros()) co = coche;
System.out.println("El mayor es  : " + co.getKilometros()); 
    
answered by 12.01.2018 в 21:28