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();
    length = name.length();
     if(length> maxLength)
      longName = name;
      System.out.print("Enter another city name <stop to quit> :");
    name = input.next();
     System.out.println(count + " were entered" );
    System.out.println("The longest was : " + longName);
5 Years
Discussion Span
Last Post by stultuske

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

Edited by zeroliken: n/a


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:

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

Edited by zeroliken: n/a


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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.