Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java program help

Tags:

java

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" "sentence2" ... ive already compiled it using javac Anagrams.java

like image 949
Homes Avatar asked Aug 09 '26 04:08

Homes


1 Answers

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.

like image 147
RoflcoptrException Avatar answered Aug 11 '26 17:08

RoflcoptrException



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!