Print “censored” if userinput contains the word “darn”. else print userinput. end with newline.

(Java Zybooks) Print "Censored" if userInput contains the word
"darn", else print userInput. End with newline. Ex: If userInput is
"That darn cat.", then output is:

Censored

Ex: If userInput is "Dang, that was scary!", then output is:

Dang, that was scary!

Note: If the submitted code has an out-of-range access, the
system will stop running the code after a few seconds, and report
"Program end never reached." The system doesn't print the test case
that caused the reported message.

import java.util.Scanner;

public class CensoredWords {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userInput;

userInput = scnr.nextLine();

/* Your solution goes here */

}
}

Answer

Note: The modified part of
the code is highlighted in grey and bold.

Screenshot of the
code:

//Import required package. import java.util.Scanner; //Define the class CensoredWords. public class CensoredWords { //Start t

Sample Output:

Im darning your socks Censored

Code to copy:

//Import required package.

import java.util.Scanner;

//Define the class CensoredWords.

public class CensoredWords

{

//Start the main() method.

public static void main (String [] args)

{

    //Create an object of the class Scanner
class.

    Scanner scnr = new Scanner(System.in);

    //Declare required variables.

    String userInput;

    //Prompt the user to input a string.

    userInput = scnr.nextLine();

    /* Your solution goes here */

    //Find the index of
string darn in the string

    //userInput using
the method indexOf(). If the

    //returned value is
not -1, then it means that

    //the word darn is
included in the string and

    //display
censored.

   
if(userInput.indexOf("darn")
!= -
1)

    {

     
System.out.println(
"Censored");

    }

   

    //Otherwise, display
the string userInput with

   
//newline.

    else

    {

     
System.out.println(userInput);

    }

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts