문제

I was looking for a little help as I'm at my wits end on how to accomplish this.

The assignment is to read in a file that contains state names, the governor of that state and the compensation he gets.

Example of the file:

California Tim John $50,000 $78,890 $30,000
North Dakota John Jones $30,000 $40,000 $56,000
Washington Susan K. Bones $30,000 $40,000 $56,000

As you can see, a name can contain more than three words (including the middle initial)

The output I'm supposed to get is the presidents name followed by the total compensation..

Example of output:

Susan K. Bones $126,000

I've already written code that prints out the total compensation. But I'm stuck on reading the names. How do I ignore the state names which can contain at most two words and just take the governor's name?

Here is my code for the total compensation.

Also note: I have to use Scanner on this.

Scanner in = new Scanner(file);
            in.nextLine();      
                do {
                    double totalCompensation = 0.0; 
                    String readLine = in.nextLine();
                    readLine = readLine.replaceAll(",", "").replace("$", " ");
                    String presidentName = "";
                    Scanner readNumber = new Scanner(readLine);
                    while(readNumber.hasNext()) {                               
                        if (readNumber.hasNextDouble()) 
                            totalCompensation += readNumber.nextDouble();
                        else {
                            readNumber.next();
                        }
                    }

Another note: don't worry, I do have a while(in.hasNextLine()) to close the do loop, later on in my code. I just don't really want to paste in the whole thing.

Any hints would be welcome! Thanks!

도움이 되었습니까?

해결책

If you KNOW ahead of time that you will only ever see US state names, you could have your code look for a state name first. Since you know what part is the state name and what part is the compensation, whatever is left must be the governor's name. There's only 50 states, so this isn't impossibly difficult.

If this is more generic and can be a city/country/whatever and not just a US, there's not a way to distinguish without a better separator character (or quotes to define the "state name" and "governor name".

EDIT: You mention that there is a further requirement that the "leader" name will be of the form "Firstname LastName" "Firstname M. Lastname" or "F. Middlename Lastname". NOW you have enough to solve the answer.

As you pull strings out with the scanner, put them in a list (or if you learned this datatype, a stack is more appropriate). Go through the list backwards. If the 2nd element is an initial, you know the name has three parts. If the 3rd element is an initial, you know the name has three parts. If neither is an initial, you know the name has two parts. Whatever is not the name of the leader is the name of the place.

다른 팁

My previous answer utterly failed to use Scanner, which was a stated requirement. As before, I am using the "New," "North," etc, prefix to delineate two word state names.

static String[] TWO_WORD_STATE_PREFIXES = new String[] {"New", "Rhode", "North", "West", "South"};

public static void scanLine(String line) {
    Scanner s = new Scanner(line);
    String stateName = s.next();

    for (String prefix : TWO_WORD_STATE_PREFIXES)
        if (stateName.equals(prefix))
            stateName += " " + s.next();

    String governorName = "";

    String nextToken;
    while (!(nextToken = s.next()).startsWith("$"))
        governorName += nextToken + " ";

    governorName = governorName.trim();

    int compensation = 0;
    while (s.hasNext())
        compensation += Integer.parseInt(s.next().replaceAll("[\\$, ]", ""));

    System.out.println(stateName + " - " + governorName + " : " + compensation);
}

public static void main(String[] args) {
    scanLine("California Tim John $50,000 $78,890 $30,000");
    scanLine("Virginia Some Guy $55,000 $71,890 $30,000");
    scanLine("South Carolina Bill F. Gates $91,000 $1,200");
    scanLine("Vermont Joan Smith $60,000 $78,890 $30,000");
    scanLine("North Dakota Tim John $50,000 $78,890 $30,000");
}

Can the file be modified to contain delimiters other than space like semi-colon. Otherwise one option i can think of is store the list of states and iterate through them and check other wise it would be a name. Eg.

List<String> stateNames={"Alabama","Alaska","Texas"};

This question is about efficient string searching. Let's work on determining which part of the string is the city or state name, since once you have that the rest is trivial.

First, you will need a list of cities and states. Here's a list of cities (should be pretty easy to parse out the actual city names) http://www.census.gov/tiger/tms/gazetteer/places2k.txt and I'm sure you can find a list of states somewhere.

Once you have that, here's a simple strategy for an efficient solution:

  • put the list of cities and states into a hashtable
  • split the input string (ex. "Califonia John Doe $213 $1232") by spaces
  • for each prefix of this list, check if the corresponding string is in the hashtable - if it is, then assume that's the state/city and parse the rest of the input accordingly.

Edit: nevermind - you added some information to the question that makes it much easier to solve. It's no longer an efficient string search problem- it's now a simple puzzle to help you practice looping in Java. See Kane's answer.

It's interesting how drastically just a little bit of information can change the scope of a problem :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top