Как подсчитать количество символов в строковом значении в массиве, а затем сравнить его с другими, чтобы найти самый длинный? - PullRequest
0 голосов
/ 29 марта 2020

Ниже то, что у меня есть сейчас. Главное, что мне просто нужно знать, - как я могу проверить количество символов строки в массиве, а затем проверить это по всем остальным записям и получить только самый большой. Вопрос, с которым я имею дело:

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

После этого программа печатает самое длинное имя и среднее число лет рождения. Если несколько имен одинаково длинны, вы можете распечатать любое из них. Можно предположить, что пользователь вводит хотя бы одного человека. Пример вывода

Себастьян, 2017 Лукас, 2017 Лили, 2017 Ханна, 2014 Габриэль, 2009

Самое длинное имя: Себастьян Среднее число лет рождения: 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();

    }
}

1 Ответ

1 голос
/ 29 марта 2020

Как подсчитать количество символов в строковом значении в массиве, а затем сравнить его с другими, чтобы найти самое длинное?

Сделайте это следующим образом:

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

Обратите внимание, что length() используется для определения длины String.

Некоторые другие важные моменты:

  1. Вам также нужна переменная хранить сумму всех лет рождения, чтобы вы могли рассчитать их среднее. Кроме того, вы можете вычислить текущее среднее значение.
  2. Обрезать записи (имя и год рождения) перед выполнением каких-либо операций с ними.
  3. Не закрывать Scanner для System.in.

Ниже приводится полная программа с примечаниями:

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));
    }
}

Примерный прогон:

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

Другой пробный прогон:

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

Еще один пробный прогон:

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

Другой пробный прогон:

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

Еще один пример:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...