简体   繁体   中英

Printing out a string array but replace a single element each time. Java

How would I go about printing out a string array multiple times and each time it replaces one of the words with a "-"? If the array had "Hello" "Hi" "Hey" then it should print

"- Hi Hey"

"Hello - Hey"

"Hello Hi -"

This is what I have so far

 public class SkipArgs
{
    public static void main(String[] args)
    { 
    int capacity = 1;
    capacity += args.length;
    String[] str = new String[capacity];

    for(int i=0; i<args.length; i++)
    {
        for (int j=0; j<args.length; j++)
        {str[j] = args[j];
        printExceptOne(str[j], i);
        }   


}
}

public static void printExceptOne(String str, int j)
{

   System.out.print(str+" ");
}
}

I don't know how to go about replacing with the "-"

The outer loop should control which array element is not printed. So it might look something like this:

for (int i = 0; i < args.length; i++) {
    for (int j = 0; j < args.length; j++) {
        // first print a separator if not the first element on the line
        if (j > 0) System.out.print(" ");

        // now print either the j-th arg or a "-"
        if (j == i) {
            System.out.print("-");
        } else {
            System.out.print(args[j]);
        }
    }
    System.out.println();
}

Let's go over your code thought

int capacity = 1;
capacity += args.length;
String[] str = new String[capacity];

That means your str array has a length of 4, that's NOT what you want. it should just be:

String[] str = new String[args.length];

Now if you don't want to use args , you need to add elements to str :

for (int i=0; i<args.length; i++)
{
    str[i] = args[i];
}

Now that we made the array you can do the following:

String temp = "";
for (int i=0; i<str.length; i++)
{
    temp = "";
    for (int j=0; j<str.length; j++)
    {
        if (i == j) 
        {
            temp = temp + "-";
        }
        else
        {
            temp =  temp + str[j];
        }
    }
    System.out.println(temp);
}

The - comes in in the below order

first line : first place second line : second place third line : third place

so based on the series this can done by equating the nested loop variables as suggested bu others. Similar we can achieve any other logic

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