¿Cómo puedo contar el número de caracteres de una cadena de valor, dentro de una matriz, y luego compararlo con otros para encontrar la más larga?

mightymorphinParkRanger:

A continuación se muestra lo que tengo en este momento. Lo principal que sólo tiene que saber es cómo puedo comprobar el número de caracteres de una cadena, dentro de una matriz, y luego comparar esa información con todas las otras entradas y sólo tirar de la más grande. La pregunta que estoy tratando es:

Escribir un programa que lea los nombres y años de nacimiento del usuario hasta que se introduzca una línea vacía. El nombre y el año de nacimiento están separados por una coma.

Después de que el programa imprime el nombre más largo y el promedio de los años de nacimiento. Si hay varios nombres son igualmente más largo, puede imprimir cualquiera de ellos. Se puede asumir que el usuario entra al menos una persona. Ejemplo de salida

sebastian, 2017, 2017 Lucas lirio, 2017 Hanna, 2014 Gabriel, 2009

nombre más largo: Normal sebastian de los años de nacimiento: 2014.8

import java.util.Scanner;
public class Test112 {

    //Asks the user for input and will print out who is the oldest


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int checkVal = 0;
        String checkName = null;

        System.out.println("Provide a name and age in this format: name,#");

        while (true) {

            //The unique thing about this code, is each input is a separate array that is not put in memory
            //You just use the array system to pull data of the values entered at that specific time
            String userIn = scanner.nextLine();

            if (userIn.equals("")) {
                break;
            } 

            //Here we get the info from the user, then split it
            String[] valArray = userIn.split(",");

            //This now uses the variable to check which value of arguments entered is the greatest
            //It'll then assign that value to the variable we created
            **if (checkVal < Integer.valueOf((int)valArray[0].length) {**
                //We need the checkVal variable to be a constant comparison against new entries
                checkVal = Integer.valueOf(valArray[1]);
                //This pulls the name of the value that satisfies the argument above
                checkName = valArray[0];
            }
        }

        System.out.println("Name of the oldest: " + checkName);
    scanner.close();

    }
}
Arvind Kumar Avinash:

¿Cómo puedo contar el número de caracteres de una cadena de valor, dentro de una matriz, y luego compararlo con otros para encontrar la más larga?

Hacerlo de la siguiente manera:

if (checkVal < valArray[0].length()) {
    checkVal = valArray[0].length();
    checkName = valArray[0];
}

Tenga en cuenta que length()se utiliza para encontrar la longitud de una String.

Algunos otros puntos importantes:

  1. También necesita una variable para almacenar la suma de todos los años de nacimiento para que pueda calcular su promedio. Alternativamente, se puede calcular el promedio de funcionamiento.
  2. Recortar las entradas (nombre de nacimiento y año) antes de realizar cualquier operación sobre ellos.
  3. No cierre la Scannerpara System.in.

A continuación se realiza el programa completo que incorpora las notas:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int checkVal = 0;
        String checkName = "", name, birthYearStr;
        int sum = 0, count = 0;

        while (true) {
            System.out.print("Provide a name and age in this format: name,#");
            String userIn = scanner.nextLine();

            if (userIn.equals("")) {
                break;
            }
            String[] valArray = userIn.split(",");
            name = valArray[0].trim();
            birthYearStr = valArray[1].trim();
            if (valArray.length == 2 && birthYearStr.length() == 4) { // Birth year should be of length 4
                try {
                    sum += Integer.parseInt(birthYearStr);
                    if (checkVal < name.length()) {
                        checkVal = name.length();
                        checkName = name;
                    }
                    count++;
                } catch (NumberFormatException e) {
                    System.out.println("Birth year should be an integer. Please try again.");
                }
            } else {
                System.out.println("This is an invalid entry. Please try again.");
            }
        }

        System.out.println("Longest name: " + checkName);
        System.out.println("Average of birth years: " + (sum / count));
    }
}

Un análisis de la muestra:

Provide a name and age in this format: name,#sebastian,2017
Provide a name and age in this format: name,#lucas,2017
Provide a name and age in this format: name,#lily,2017
Provide a name and age in this format: name,#hanna,2014
Provide a name and age in this format: name,#gabriel,2009
Provide a name and age in this format: name,#
Longest name: sebastian
Average of birth years: 2014

Otra muestra de la ejecución:

Provide a name and age in this format: name,#sebastian,201
This is an invalid entry. Please try again.
Provide a name and age in this format: name,#sebastian,hello
This is an invalid entry. Please try again.
Provide a name and age in this format: name,#sebastian,2017
Provide a name and age in this format: name,#lucas,2017
Provide a name and age in this format: name,#lily,2017
Provide a name and age in this format: name,#hanna,2014
Provide a name and age in this format: name,#gabriel,2009
Provide a name and age in this format: name,#
Longest name: sebastian
Average of birth years: 2014

Otra muestra de la ejecución:

Provide a name and age in this format: name,#hello,2018,sebastian,2017
This is an invalid entry. Please try again.
Provide a name and age in this format: name,#hello,2018
Provide a name and age in this format: name,#sebastian,2017
Provide a name and age in this format: name,#
Longest name: sebastian
Average of birth years: 2017

Otra muestra de la ejecución:

Provide a name and age in this format: name,#sebastian,rama
Birth year should be an integer. Please try again.
Provide a name and age in this format: name,#sebastian,12.5
Birth year should be an integer. Please try again.
Provide a name and age in this format: name,#sebastian,2017
Provide a name and age in this format: name,#abcdefghi,2018
Provide a name and age in this format: name,#rama,2009
Provide a name and age in this format: name,#
Longest name: sebastian
Average of birth years: 2014

Otra muestra de la ejecución:

Provide a name and age in this format: name,#sebastian,2017
Provide a name and age in this format: name,#lucas,2017
Provide a name and age in this format: name,#lily   ,          2017
Provide a name and age in this format: name,#
Longest name: sebastian
Average of birth years: 2017

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=359724&siteId=1
Recomendado
Clasificación