接受5个名字并打印最长的名字?

时间:2015-09-23 11:10:34

标签: java compareto string-length

我想要5个给定名字的最长名称。我想我应该使用compareTo()方法或length()

输出必须如下:

enter 5 names :
Joey
Mark
Catherine
Zachery
Foster

Longest name is Catherine.

我应该使用什么方法以及如何使用?到目前为止,这是我的代码:

Scanner x = new Scanner(System.in);
String name = ""
System.out.print("Enter 5 names");
name = x.nextLine();
name2 = x.nextLine();
name3 = x.nextLine();
name4 = x.nextLine();
name5 = x.nextLine();

if(name.compareTo(name2)>0)  //is this method right?

8 个答案:

答案 0 :(得分:2)

.compareTo告诉你哪个字符串以字典顺序排在第一位(< 0如果s1< s2,如果s1 = = s2则为0,如果s1> s2则为0)

String s1 = "abc";
String s2 = "def";
s1.compareTo(s2) < 0;

.length()返回字符串的长度

s1.length()==3;

在您的情况下,您需要根据长度进行比较,因此您需要后者。如果它只有5个名字,你可以拿第一个并假设它是最长的,然后通过保持&#34;最长到目前为止,逐个读取其他名称&#34;保存并比较它们来。毕竟,你只关心最长的。

如果你希望它们按长度排序,同时仍然保留它们,你需要将它们存储在某种集合(列表,数组)中,然后根据长度对它进行排序。

问题很简单,所以我不会直接提供代码,试着自己动手,你可以这样做:)

答案 1 :(得分:0)

这是一个适用于任意数量条目的解决方案:

Scanner x = new Scanner(System.in);
String name = "", temp="";

while (x.hasNextLine()){
    temp = x.nextLine();
    if (temp.length() > name.length()) name = temp;
}

System.out.println("Longest is " + name);

您需要Ctrl + Z来结束Windows上的inputStream

答案 2 :(得分:0)

这个怎么样?

Scanner in = new Scanner(System.in);
// no need to have 5 all over the code.
// Define it once to avoid "magic nubmers"
int namesCount = 5;
// fun fact: shortest name is always "". We don't have to use null
String longestName = "";
System.out.print("Enter " + nameCount + " names:");
for (int i=0; i< nameCount; i++){
    // store new name from user
    String candidate = in.readLine();
    // is this one longer than the current longest?
    if (longestName.length() < candidate.length()){
        // found a longer name
        longestName = candidate;
    }
}
System.out.println("Longest name is " + longestName); 

这会放弃存储名称,因为它似乎只使用最长的名称。它还概括了要迭代的名称数量,最重要的是变量名称是有意义的名称。

答案 3 :(得分:0)

一种简单的方法是for循环来读取5个名称并找到最大名称的长度。使用for循环可以避免创建5个威慑字符串变量。

如果您想稍后使用这些名称,可以使用String数组。

public static void main(String[] args) throws IOException {
    Scanner x = new Scanner(System.in);
    String name = "";
    String maxName = "";
    int maxLength = 0;

    System.out.println("enter 5 name :");

    for (int i = 0; i < 5; i++) { // read 5 names
        name = x.nextLine();
        if (maxLength < name.length()) { // check longest name
            maxLength = name.length();
            maxName = name;              // store in temp variable to show
        }
    }
    System.out.println("Longest name is " + maxName); // print largest name
}

输出:

  

输入5个名字:
  拉吉
  SITA
  梵歌
  慕克吉
  丽塔
  最长的名字是mukherjee

答案 4 :(得分:0)

import java.util.Scanner;

public class LenghtyName {

    public static void main(String[] args) {

        Scanner x = new Scanner(System.in);
        /*
         Instead of declaring 5 different String variable
         just use String array with size = 5
         */
        String[] names = new String[5];

        System.out.print("Enter 5 names :");

        names[0] = x.nextLine();
        names[1] = x.nextLine();
        names[2] = x.nextLine();
        names[4] = x.nextLine();
        names[5] = x.nextLine();

        //Assume lenthyName as empty String
        String lengthyName = "";

        /*
         Iterate over String array using for-each loop
         */
        for (String name : names) {
            /*
             -Check null to avoid NullPointerException
             -Trim the left and right blank space in name by #trim()
             -Compare current name length with lengthyName if greater 
             replace the lengthyName by current name.
             */
            if (name != null && name.trim().length() > lengthyName.length()) {
                lengthyName = name;
            }
        }

        /*
         Print length name
         */
        System.out.println("Longest name is " + lengthyName);
    }
}

答案 5 :(得分:0)

这是一个应该有效的解决方案:

public class LongestWord {

    public static String getLongestString(String[] array) {
          int maxLength = 0;
          String longestString = null;
          for (String s : array) {
              if (s.length() > maxLength) {
                  maxLength = s.length();
                  longestString = s;
              }
          } 
          return longestString;
      }

      public static void main(String[] args) {
          String[] toppings = {"Cheeddddddddddse", "Pepperoni", "Black Olivesddd"};
          String longestString = getLongestString(toppings);
          System.out.format("longest string: '%s'\n", longestString);
      }

}

答案 6 :(得分:0)

这是我的代码,用于按长度比较3个输入字符串:

public static void main(String[] args) {

    String string1 , string2 , string3;

    Scanner input = new Scanner(System.in);
    System.out.println("Enter three string names to compare");
    string1 = input.nextLine();
    string2 = input.nextLine();
    string3 = input.nextLine();

    if (string1.length()>string2.length()) {
        if (string1.length() > string3.length())
            System.out.println("String 1 has the longest length , length = "+string1.length());
    }

    if (string2.length()>string1.length()){
        if(string2.length()>string3.length())
            System.out.println("String 2 has the longest length , length = "+string2.length());
    }

    if (string3.length()>string1.length()) {
        if (string3.length() > string2.length())
            System.out.println("String 3 has the longest length , length = " + string3.length());
    }

}

答案 7 :(得分:0)

//SIMPLE JAVA SOLUTION
class GFG 
{
    String longest(String names[], int n)
 {
        String res="";
        for(int i=0;i<n;i++)
        {
            if(res.length()<names[i].length())
            {
                res=names[i];
            }
        }
        return res;
        
    }
}