Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
if n=4, then output should be
4
4x
4x2
4x21

here, multiples of 3 has been replaced by "x". Please tell me the logic of how to replace like this.

What I have tried:

class Main {
  public static void main(String[] args) {
    int n=4;
    int num=n;
    String str="";
    for(int i=1;i<=n;i++)
    {
      str=str+num;
      num--;
    System.out.println(str);
    }
    
    
  }
}
Posted
Updated 13-Mar-18 20:16pm

Check whether str contains value 3. If contains, replace 3 with x
if (str.contains("3")) {
     str = str.replace("3", "x");
  }

To make all multiples of 3 replace by x , use below condition
if (num % 3 == 0) {
     str = str.replace(String.valueOf(num), "x");
}
 
Share this answer
 
v3
Comments
Member 13724614 14-Mar-18 2:09am    
Sir the question is of all the multiples of 3 and not just 3. If I put the n=8, then????
wseng 14-Mar-18 3:31am    
I have edited my answer.
class Main {
  public static void main(String[] args) {
    int n=8;
    int num=n;
    String str="";
    for(int i=1;i<=n;i++)
    {
      if(str.contains("3"))
      {
        str=str.replace("3","x");
      }
      str=str+num;
      num--;
      System.out.println(str);
    }
    
    
  }
}

According to your given logic, its output is coming out to be
8
87
876
8765
87654
876543
87654x2
87654x21
which is wrong. I want this output
8
87
87x
87x5
87x54
87x54x
87x54x2
87x54x21
 
Share this answer
 
Comments
wseng 14-Mar-18 3:30am    
This is not an answer. You should edit your post instead of posting it as a solution.
Member 13724614 14-Mar-18 10:36am    
i know this is not an an answer. But the column says" what you have tried" and not "give the exact solution. I am asking people to correct it as I have already said that I am not able to get the output.
wseng 14-Mar-18 21:27pm    
have you tried my answer ?
Member 13724614 15-Mar-18 17:32pm    
yes i have tried but the output is not coming
wseng 15-Mar-18 21:53pm    
You mean nothing come out ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900