开发者

Java program help

I made a class Anagrams that writes the permutations of the words in a sentence and when I run the compiled program as java Anagrams "sentence1" "sentence2"... It should generate the permutations of each of the sentences. How would I get it to do that?

import java.io.*;
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;

public class Anagrams
{

    ...

    public static void main(String args[])
    {
        String phrase1 = "";
        System.out.println("Enter a sentence.");
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        try { phrase1 = input.readLine(); }
        catch (IOException e) {
        System.out.println("Error!");
        System.exit(1);
        }

        System.out.println();
        new Anagrams(phrase1).printPerms();
    }


}

this is what i have so far i just need it to run on "sentence1" "sentence2" ... when i type the command java Anagrams "sentece1" "sen开发者_JAVA百科tence2" ... ive already compiled it using javac Anagrams.java


From your comment I think your only question is how to use command line arguments to solve the task:

Your main method is looking like this:

public static void main(String args[])

but should look like this

public static void main(String[] args)

You see that there is an array of strings that holds the command line arguments. So if your executing your code with

java Anagrams sentence1 sentence2

Then the array has the length 2. In the first place (args[0]) there is the value sentence1 and in the second place (args[1]) there is the value sentence2.

An example code that prints all your command line arguments looks like this:

public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }

Now you should be able to use your anagram algorithm for each command line argument.


Here's a simple example of getting the arguments from the command line.

Bear in mind that this is open to "IndexOutOfBoundsException"s if you don't provide enough arguments, so make sure to check that in your code!

class ArgsExample {
    public static void main(String[] args) {
        System.out.println(args[0]);
        System.out.println(args[1]);

    }

}

C:\Documents and Settings\glow\My Documents>javac ArgsExample.java

C:\Documents and Settings\glow\My Documents>java ArgsExample "This is one" "This
 is two"
This is one
This is two

C:\Documents and Settings\glow\My Documents>


Varargs would allow you to use an indeterminate number of strings in a method signature, if that's what you're looking for. Otherwise, Roflcoptr is right if it's a question of passing arguments into main.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜