Home > OS >  Want to print the names which ends up with the letter "a" , Java
Want to print the names which ends up with the letter "a" , Java

Time:06-20

Basically i want to print the names which ends up with the letter "a", and count how many percentage those names are. I was trying some "charAt" stuff but i couldnt jump over it.

String[] array = new String[10];

Scanner sc = new Scanner(System.in);

System.out.println("ENTER THE NAMES");
String name = sc.nextLine();

for (int i = 0; i < array.length; i  ) {
    array[i] = sc.nextLine();
    if (name.length() < array[i].length()) {
        name = array[i];
    }
}
System.out.println("LONGEST NAME: "   name);

for (int i = 0; i < array.length; i  ) {
    if (name.length() > array[i].length()) {
        name = array[i];
    }
}
System.out.println("SHORTEST NAME: "   name);

for (int i = 0; i < array.length; i  ) {
    if (name.endsWith("a")) {
        System.out.println(name);
    }
}

CodePudding user response:

You don't update the value of name to array[i], so you basically loop over the same value ten times. This should solve it:

for (int i = 0; i < array.length; i  ) {
    name = array[i];
    if (name.endsWith("a")) {
        System.out.println(name);
    }
}

Another possibility is to use array[i] instead of name (but as you use it more than once, it's better to use the first solution):

for (int i = 0; i < array.length; i  ) {
    if (array[i].endsWith("a")) {
        System.out.println(array[i]);
    }
}

CodePudding user response:

  1. Do you realy need to loop three times offer the same array?

  2. Try to use variables more often. Reminde that each array[i] is an access to the array same for array[i].length()

  3. name.endsWith("a") is not right if you were looking at the names in the array for the loop it should be array[i].endsWith("a")

    String[] array = new String[10];
    
    Scanner sc = new Scanner(System.in);
    
    System.out.println("ENTER THE NAMES");
    String name = sc.nextLine();
    
    String shortest = name;
    String longest = name;
    
    for (int i = 0; i < array.length; i  ) {
        array[i] = sc.nextLine();
        String currentName = array[i];
        int length = currentName.length();
    
        if (longest.length() < length) {
            longest = currentName;
        }
        if (shortest.length() > length) {
            shortest = currentName;
        }
        if (currentName.endsWith("a")) {
            System.out.println(currentName);
        }
    }
    System.out.println();
    System.out.println("LONGEST NAME: "   longest);
    System.out.println("SHORTEST NAME: "   shortest);
    
  • Related