简体   繁体   中英

How do I loop over arguments java?

I have to create lots of files to hold outputs for different objects, and I wondered if there was an easy way using loops, rather than typing out the whole thing every time. Currently, I am doing it like this, which quickly becomes unwieldy:

public void createFile(String fn, String fn1, String fn2, String fn3, String fn4, String fn5, String fn6){
    java.io.File filei = new java.io.File("fn.txt" );       
    java.io.PrintWriter earth1 = new PrintWriter(file);
    java.io.File file1 = new java.io.File("fn1.txt" );
    java.io.PrintWriter sun1 = new PrintWriter(file1);
    java.io.File file2 = new java.io.File("fn2.txt" );
    java.io.PrintWriter mercury1 = new PrintWriter(file2);
    java.io.File file3 = new java.io.File("fn3.txt" );
    ...etc
}

So manually writing out the lines for a new file. The string fn will have the value earth, fn1 will be sun, fn2 mercury etc. I want to use a for-loop ideally, but don't know how to loop over arguments! For example I need a way to make a loop recreate this pattern:

java.io.File filei = new java.io.File("fn.txt");
java.io.PrintWriter fn1 = new PrintWriter(filei);

java.io.File filei = new java.io.File("fn1.txt");
java.io.PrintWriter (fn1)1 = new PrintWriter(filei);

I need a printwriter and file for every argument. The printwriter needs have a name which is the argument with the number one appended. The file needs to be named 'argument.txt', so fn.txt, fn1.txt etc, which I'm not sure my code will currently achieve. I suspect it will literally name the files fn, fn1 etc rather than using the string the arguments represent, but can't check until I've completed my changes, for which I need the loop.

This is not concise, and may not be clear. If unclear, let me know, I'll try and word it better.

Pass a List<String> , or a String[] as argument, rather than passing 6 Strings.

Or put all those Strings in an array at the beginning of the method, and loop over that array.

Or use a vararg parameter, which allows passing as many Strings as argument (from the caller), while receiving an array in the method:

public void createFile(String... fn) {
    for (String f : fn) {
        ...

And in the caller:

createFile("a", "b", "c");

正如JB Nizet所建议的那样,但我建议的最佳方法是o使用列表文件名作为输入参数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM