-1

Instead of hard coding to read the infile and outfile, I want to read from the command line. How would I do that?

/**
 * reads a file and creates a histogram from it
 * @param args string of argument
 * @precondition none
 */
public static void main(String[] args) {
    Histogram hist = new  Histogram();
    FileInputController input = new FileInputController(hist);
    FileOutputController output = new FileOutputController(hist);

    try {
        input.readWords("infile.txt");
        output.writeWords("outfile.txt");
    } catch (FileNotFoundException exception) {
        System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
    } catch (IOException exception) {
        System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
    } finally {
        System.exit(1);
    }
 }
  • 1
    https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html – Reimeus Oct 06 '15 at 13:54
  • use `args`. something like `java helloworld.java file1.txt` – sam Oct 06 '15 at 13:54
  • Possible duplicate of [How can I get the user input in Java?](http://stackoverflow.com/questions/5287538/how-can-i-get-the-user-input-in-java) – Tom Oct 06 '15 at 14:09

2 Answers2

1
public static void main(String[] args) {
    WordHistogram hist = new  WordHistogram();
    FileInputController input = new FileInputController(hist);
    FileOutputController output = new FileOutputController(hist);

    try {
        input.readWords(args[0]);  //args[0] is the first argument passed while launching Java
        output.writeWords(args[1]);  //args[1] is the second argument passed while launching Java
    } catch (FileNotFoundException exception) {
        System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
    } catch (IOException exception) {
        System.out.println("exception caught! somthing went wrong: " + exception.getMessage());
    } finally {
        System.exit(1);
    }
}

Run your program like: java YourClassName infile.txt outfile.txt

In main(String[] args), args is an array of Strings which contains values of arguments passed while launching Java.

Please DO read Oracle docs about command line arguments for further reading.

hagrawal
  • 12,025
  • 4
  • 33
  • 61
0

to get integer value use like this

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

to get string use this

Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();

and for output use just System.out.println("your text here");

Asif Mehmood
  • 467
  • 3
  • 16