Problem with the && in if statement

Hello everybody,

I was trying to finish a puzzle from a battle of clash on my pc when i run into a weird situation.

The goal of the puzzle was to switch all the character from the first string to ‘-’ if they didn’t appear in the second string and show the result. When i finnaly thought i cracked the code, i realized my code don’t work in some cases but for unknown reason. I know where it comes from but i don’t understand why…

here is the code:

public class Solution {
    public static void main(String[] args) {
       Scanner in = new Scanner(System.in);
       String a = in.nextLine();
       String b = in.nextLine();
       char[] tabA = a.toCharArray();
       char[] tabB = b.toCharArray();
       int i = 0, j = 0;
       while(i<tabA.length){
         if(tabA[i]!=tabB[j] && j<tabB.length){
           tabA[i] = '-';
         }else{
           j++;
         }
         i++;
       }
       a = new String(tabA);
       System.out.println(a);
       }
}

I don’t understand why the code is checked at the if line since j is > to tabB.lenght…

thank you for your help and time.

Your code is too ugly to read. Could you format it?

My bad.

Should be better.

You are trying to do it by a single while loop.
I guess it needs two loops nested.

create a new array, same length as arrA, init with '-'
loop through every ch from arrB
    loop through arrA
        if arrA contains this ch
            write this ch in the new array at the same index of arrA
        else do nothing
replace arrA by the new array

Assuming this is about a clash I did some time ago: Coding Games and Programming Challenges to Code Better

There are a couple mistakes: the while loop goes out of bounds for tabB (you will call tabB[j] with values of j >= tabB.length), and you don’t factor in the possibility that the subsequence may occur before reaching the end of the string a, like in this testcase:

Input:

hellothere
hello

Output:

hello-----

You can try to solve those two by yourself if you want in the IDE of the previous link. Your approach is the correct one.

Otherwise, this is a possible solution in Java:
import java.util.*;


public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        char[] tabA = in.nextLine().toCharArray();
        char[] tabB = in.nextLine().toCharArray();
        
        int i = 0, j = 0;
        while (i < tabA.length && j < tabB.length) {
            if (tabA[i] != tabB[j]) {
                tabA[i] = '-';
            } else {
                j++;
            }
            i++;
        }
        // Right trailing
        while (i < tabA.length) tabA[i++] = '-';

        System.out.println(new String(tabA));
    }
}

Thank you all for your reply and expertise ! I understand and i will try to rewrite it !