Domanda

I know I'm not supposed to do this but I am a beginner and I need help on this. I am wondering what I need in each number on the bottom. I am not asking for the code but just help on what to use.

http://i.imgur.com/elSuPgW.png

Clarification:

What the problem is asking for is to go through the String one character at a time.

A "valid" word is written backwards in between ? and &

example: valid would be encrypted as ?dilav&

The entire message of encrypted words are also in reverse order.

I hope I made it more clear

È stato utile?

Soluzione

Start by thinking how you would solve this in your head.

You would start at the left and look at each character until you found a '?'. Then you would note the letters until you found a '&'. Bingo, first word. Continue until you have all the words.

Now you know how many words you have (answer #2).

Then you need to reverse the letters in each word.

Now print them in the order you found them (answer #3).

Now print them in reverse order - the last word first (answer #4).

Now print the reversed list with spaces between them (answer #5).

Sample code (please try to understand how it works and don't just copy it and hand it in - or your teacher will ask you to explain how it works):

public static void main(final String[] args){

    // example provided by Jason via Stackoverflow

    String message = "&*#$@?ebyam,&?siht&=asdf???od&failure???&?on?nac&the%%@?uoy&horizon!";

    System.out.println("#1: " + message.length());

    List<String> words = new ArrayList<String>();
    int questionPos = message.indexOf("?");
    while(questionPos > -1) {
        message = message.substring(questionPos + 1, message.length());

        int ampersandPos = message.indexOf("&");
        questionPos = message.indexOf("?");

        if(ampersandPos > 0 && (ampersandPos < questionPos || questionPos == -1)) {
            String word = message.substring(0, ampersandPos);
            StringBuilder reversedWord = new StringBuilder();
            for(int i = word.length() - 1; i >= 0; i--) {
                reversedWord.append(word.charAt(i));
            }
            words.add(reversedWord.toString());
        }
    }

    System.out.println("#2: " + words.size());

    System.out.println("#3:");
    for(final String word : words) {
        System.out.println(word);
    }

    System.out.println("#4:");
    for(int i = words.size() - 1; i >= 0; i--) {
        System.out.println(words.get(i));
    }

    System.out.print("#5: ");
    for(int i = words.size() - 1; i >= 0; i--) {
        if(i < words.size() - 1) {
            System.out.print(" ");
        }
        System.out.print(words.get(i));
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top