-3

Python has the in operator which makes it simple. but how do i implement the below python concept in java since java doesnt have the in operator. This is a Python program

secret_word = "python"
correct_letters = "oy"
count = 0
while count < len(secret_word):
    print(secret_word[count] if secret_word[count] in correct_letters else '_', end=" ")
    count += 1
hameed
  • 87
  • 1
  • 1
  • 7

2 Answers2

1

You can mimic this with the ternary operator and String.indexOf:

System.out.println(correct_letters.indexOf(secret_word.charAt(count)) > -1 ? secret_word.charAt(count) : '_')

That said, you should follow @Peter's advice and use a regular expression replace:

System.out.println(secret_word.replaceAll("[^" + Pattern.quote(correct_letters) + "]","_"));
Darth Android
  • 3,437
  • 18
  • 19
0

You wouldn't do it like this at all. I would use a regex.

String secret_word = "python";
String correct_letters = "oy";
System.out.println(secret_word.replaceAll("[^"+correct_letters+"]", "_"));

This would mask all the letters except the correct one. I suspect you can use regex in python as well.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130