i have to create a city application that prompts the user for a series of city names and then displays the number of city names entered and then the name of the city with the most characters in uppercase letters.
how come it always output the last name entered ?

import java.util.Scanner;
 
public class Cities
{
  public static void main(String[]args)
  {
    Scanner input = new Scanner(System.in);
    int maxLength = 0;
    int length = 0;
    int count = 0;
    String longName = "";
    System.out.print("Enter a city name <stop to quit> :");
    String name = input.nextLine();
     while(!(name.equals("stop")))
    {
    length = name.length();
     if(length> maxLength)
      longName = name;
      System.out.print("Enter another city name <stop to quit> :");
    name = input.next();
    count++;
    }
     System.out.println(count + " were entered" );
    System.out.println("The longest was : " + longName);
 
  }

Recommended Answers

All 5 Replies

You don't have a process where you save a new value for maxlength

in your case maxlength should have a value equal to the current city name that has the most uppercase letters

Since the last city name has a length greater than 0 it will output the last city name

Add the following tweak in your while loop and you will be good to go

if (length > maxLength) {
                longName = name;
                [B]maxLength = longName.length();[/B]
            }

or, don't save the length, since you're not really using it:
save the name with the greatest length so far
when you enter a new name:

//... 
counter++;
if ( input.length() > storedName.length())
 storedName = input;
//...

@stultuske and fakerz

he needs the name of the city with the most characters in uppercase letters and I don't think using length() alone is enough... well in the codes you presented anyway

as far as I understood: he needs to display the name of the city with the most letters, but he must display it in uppercases.
I might be wrong in this, but then it's to the OP to describe his needs in a way that is clear to anyone.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.