Censored Words Condition - java

I need this program to print "Censored" if userInput contains the word "darn", else print userInput, ending with newline.
I have:
import java.util.Scanner;
public class CensoredWords {
public static void main (String [] args) {
String userInput = "";
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine;
if(){
System.out.print("Censored");
}
else{
System.out.print(userInput);
}
return;
}
}
Not sure what the condition for the if can be, I don't think there is a "contains" method in the string class.

The best solution would be to use a regex with word boundary.
if(myString.matches(".*?\\bdarn\\b.*?"))
This prevents you from matching sdarnsas a rude word. :)
demo here

Try this:
if(userInput.contains("darn"))
{
System.out.print("Censored");
}
Yes that's right, String class has a method called contains, which checks whether a substring is a part of the whole string or not

Java String Class does have a contains method. It accepts a CharSequence object. Check the documentation.

Another beginner method would be to use the indexOf function. Try this:
if (userInput.indexOf("darn") > 0) {
System.out.println("Censored");
}
else {
System.out.println(userInput);

Related

Just some quick questions on using string

We have to make a program on printing initials, which seems pretty easy ok, but I don't know how to cut the string when the input is all on one line using the scanner class in.nextline();. I cant seem to find a way to cut the string using only string methods. Also, another problem arose when I have to also be able to adjust if there isn't a middle name either. if anyone can help me or lead me in the right direction that would be nice.
If you can use split function as you can see below:
String inputString=s.nextLine();
String [] str = inputString.split(" ");
If you want to have extract only first letter then -
import java.util.Scanner;
public class TestStringInput {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter the Name");
String input = scan.nextLine();
int value = input.indexOf(" ",input.indexOf(" "));
String result = input.substring(0,value);
System.out.println(result);
}
}
But if you want to Extract Starting 2 Initials then change this line-
int value = input.indexOf(" ",input.indexOf(" ")+1);
As Stephen mentioned, your question is about Java, consider re-tagging.
You can use a for loop to iterate through the string. Remember a string is an object. It would help a lot if you posted your code.
import java.util.Scanner;
public class HW03 {
public static void main (String args[])
{
Scanner in = new Scanner(System.in);
String str = "";
System.out.println("What are your first, middle and last names?");
str = in.nextLine();
}
}

Recursive Palindrome Checker

This method only works for small inputs such as xox but not with a more complex input like taco cat. I have read this code repeatedly and have not been able to fix the problem. I assume there is a tiny error as I have changed the code structurally trying to tweak my approach and have not been able to fix it.
import java.util.Scanner;
public class Palindromes
{
static Scanner scan = new Scanner(System.in);
public static void main (String[] args)
{
System.out.println("Enter a string, human:");
String s=scan.nextLine();
if(palindrome(s)){
System.out.print("This is a palindrome, I am amused Earthling.");
}else{
System.out.print("Don't you know to speak only in palindromes to your alien Overlord?");
}
}
public static boolean palindrome(String s){
s.replace(" ","");
if(s.length()<2){
return true;
}else if(s.charAt(0)==s.charAt(s.length()-1)){
return palindrome(s.substring(1,s.length()-2));
}else{
return false;
}
}
}
Two things to fix:
You forgot to assign the result of replace back to s, resulting in you ignoring the result with spaces removed. Try:
s = s.replace(" ","");
You have an off-by-one error when taking the substring to pass to the recursive call. The ending index of substring is exclusive, so you are trimming one too many characters off the end of the substring. Try:
return palindrome(s.substring(1,s.length()-1));

String.replace() method not printing full string in java

I'm trying to do some homework for my computer science class and I can't seem to figure this one out. The question is:
Write a program that reads a line of text and then displays the line, but with the first occurrence of hate changed to love.
This sounded like a basic problem, so I went ahead and wrote this up:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = keyboard.next();
System.out.println("I have rephrased that line to read:");
System.out.println(text.replaceFirst("hate", "love"));
}
}
I expect a string input of "I hate you" to read "I love you", but all it outputs is "I". When it detects the first occurrence of the word I'm trying to replace, it removes the rest of the string, unless it's the first word of the string. For instance, if I just input "hate", it will change it to "love". I've looked at many sites and documentations, and I believe I'm following the correct steps. If anyone could explain what I'm doing wrong here so that it does display the full string with the replaced word, that would be fantastic.
Thank you!
Your mistake was on the keyboard.next() call. This reads the first (space-separated) word. You want to use keyboard.nextLine() instead, as that reads a whole line (which is what your input is in this case).
Revised, your code looks like this:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = keyboard.nextLine();
System.out.println("I have rephrased that line to read:");
System.out.println(text.replaceFirst("hate", "love"));
}
}
Try getting the whole line like this, instead of just the first token:
String text = keyboard.nextLine();
keyboard.next() only reads the next token.
Use keyboard.nextLine() to read the entire line.
In your current code, if you print the contents of text before the replace you will see that only I has been taken as input.
As an alternate answer, build a while loop and look for the word in question:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
// Start with the word we want to replace
String findStr = "hate";
// and the word we will replace it with
String replaceStr = "love";
// Need a place to put the response
StringBuilder response = new StringBuilder();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
System.out.println("<Remember to end the stream with Ctrl-Z>");
String text = null;
while(keyboard.hasNext())
{
// Make sure we have a space between characters
if(text != null)
{
response.append(' ');
}
text = keyboard.next();
if(findStr.compareToIgnoreCase(text)==0)
{
// Found the word so replace it
response.append(replaceStr);
}
else
{
// Otherwise just return what was entered.
response.append(text);
}
}
System.out.println("I have rephrased that line to read:");
System.out.println(response.toString());
}
}
Takes advantage of the Scanner returning one word at a time. The matching will fail if the word is followed by a punctuation mark though. Anyway, this is the answer that popped into my head when I read the question.

Can I use startsWith and endsWith in Java to check input?

In Java can I use startsWith and endsWith to check a user input string? Specifically, to compare first and last Characters of the input?
EDIT1: Wow you guys are fast. Thank you for the responses.
EDIT2: So CharAt is way more efficient.
So How do I catch the First and last Letter?
char result1 = s.charAt(0);
char result2 = s.charAt(?);
EDIT3: I am very close to making this loop work, but something is critically wrong.
I had some very good help earlier, Thank you all again.
import java.util.Scanner;
public class module6
{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
while(true){
System.out.print("Please enter words ending in 999 \n");
System.out.print("Word:");
String answer;
answer = scan.next();
char aChar = answer.charAt(0);
char bChar = answer.charAt(answer.length()-1);
String MATCH = new String("The word "+answer+" has first and last characters that are the same");
String FINISH = new String("Goodbye");
if((aChar == bChar));
{
System.out.println(MATCH);
}
if(answer !="999")
{
System.out.println(FINISH);
break;
}
}
}
}
The loop just executes everything, No matter what is input. Where did I go wrong?
In Java can I use startsWith and endsWith to check a user input string?
You certainly can: that is what these APIs are for. Read the input into a String, then use startsWith/endsWith as needed. Depending on the API that you use to collect your input you may need to do null checking. But the API itself is rather straightforward, and it does precisely what its name says.
Specifically, to compare first and last Characters of the input?
Using startsWith/endsWith for a single character would be a major overkill. You can use charAt to get these characters as needed, and then use == for the comparison.
yes, you should be able to do that and it should be pretty striaghtforward. Is there a complexity that you are not asking?
Yes, in fact, not just characters, but entire strings too.
For example
public class SOQ4
{
public static void main(String[] args)
{
String example = "Hello there my friend";
if(example.startsWith("Hell"))
{
System.out.println("It can do full words");
}
if(example.startsWith("H"))
{
System.out.println("And it can also do letters");
}
if(example.endsWith("end"))
{
System.out.println("Don't forget the end!");
}
if(example.endsWith("d"))
{
System.out.print("Don't forget to upvote! ;)");
}
}
}
I recommend you use the API, here's a link to it http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Simple Substring Issue

My teacher wants us to make a letter 'o' move around the console. The letter 'o' has been coded to appear in the center of the console screen. I have already created the movingRight and movingDown methods but I'm having difficulty creating the movingLeft and movingUp methods. Here is my code:
import java.util.Scanner;
public class Main {
static String letter = "\n\n\n\n O";
String whenmovingup = letter.substring(0, 1);
char whenmovingleft = letter.charAt(letter.length() - 2);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(letter);
input.nextLine();
if (input.equals("left")) {
movingLeft();
}
if (input.equals("right")) {
movingRight();
}
if (input.equals("up")) {
movingUp();
}
if (input.equals("down")) {
movingDown();
}
}
public static void movingRight(){
letter = " " + letter;
}
public static void movingDown(){
letter = "\n" + letter;
}
public static void movingLeft(){
letter.remove(whenmovingleft);
}
public static void movingUp(){
letter.remove(whenmovingup);
}
}
I'm having an issue with removing the whenmovingfeft and whenmovingup substrings from my original string letter. It's giving an error ('The method remove(char) is undefined for the type String'), and I'm not sure what needs to be done.
Does anyone know how this can be resolved?
Thanks in advance for all responses.
There is no remove method for a string. However, there is a replace method that may do what you want. Note that it does not modify the string object, but it returns a new string. So you would do:
letter = letter.replace(whenmovingup, "");
Note that there are two slightly different overloads of replace which do different things depending on whether you ask it to remove a String or char. The replace(String, String) method replaces one occurrence, while the replace(char, char) replaces all occurrences. You want just one, so declare whenmovingleft as a String and initialise it appropriately.

Categories