How do I use the contains method with "if, else" statement? - java

I am having difficulty triggering my "if" statement. When I input "I like my 'anything'", which the CharSequence should be searching for, the code kicks out the error from the else statement. I've tried to see if the contains method wasn't reading whitespace by attempting to identify just one letter using the CharSequence. That didn't help. I also attempted to change my contains method into a boolean and run the if statement if the boolean were true. That also did not work. I've searched around a bit at other code and it seems to look similar. Eclipse isn't flagging any errors I'm just beginning and have little clue on what else to attempt. If there are any additional hints on how to clean my code up or methods that might work better. Please give some constructive criticism.
import java.util.Scanner;
public class hello {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
try {
System.out.println("Hi, what is your name?");
String name1 = scan.next();
System.out.println("Hello "+ name1 + ". Tell me what you like about yourself?\n"
+ "Please pretext what you like about yourself with the phrase 'I like my'.");
String selfEsteem = scan.next();
CharSequence searchString = "I Like my";
if (selfEsteem.contains(searchString)) {
selfEsteem = selfEsteem.replace("my", "your");
System.out.println(selfEsteem + "also.");
} else {
System.err.println("Error: User did not use 'I like my' input format");
}
} finally {
scan.close();
}
}
}
output:
Hi, what is your name?
Janet
Hello Janet. Tell me what you like about yourself?
Please pretext what you like about yourself with the phrase 'I like my'.
I like my boobs
Error: User did not use 'I like my' input format

Your searchString is "I Like my", while your text has "I like my". So I assume your user will enter the lowercase one and contains is case sensitive so it won't find it.
Change to:
CharSequence searchString = "I like my";

You are searching for "I Like my" while your error massages says it should be 'I like my'.
It's case sensitive.
Either type in "I Like my" or change your searchString to "I like my".

Use
if (selfEsteem.containsIgnoreCase(searchString))
...
instead of
if (selfEsteem.contains(searchString))
...
Then it doesn't matter what case the user types in.

Related

How to get the Java Scanner utility to input twice

so heres my code
public class Practice01{
public static void main (String[] args){
System.out.println("Hi there");
Scanner scr = new Scanner(System.in);
String response = scr.nextLine();
if (response.equalsIgnoreCase("hello") || response.equalsIgnoreCase("hi") || response.equalsIgnoreCase("hey")) {
System.out.println("Oh, well arent you well-mannered. Hello there, how are you?");}
else {
System.out.println("Invalid Input");
String responseG;
responseG = scr.nextLine();
if (responseG.equalsIgnoreCase("good")) {
System.out.println("Glad to hear");
}
}
}
}
im a bit of a noobie when it comes to java, I just started today, but after the else statment here, java terminates itself for some reason, and it just doesnt care about the rest of the code. I was looking online and I saw that if you wanted to take another input you used the .nextLine(); function (i dont think its called a function but you know what I mean) but after I type either hey, hello, or hi, it prints "Oh, well arent you well-mannered. Hello there, how are you?" and then I cant type anything else, and it says < terminated > . can anyone help? thanks
Edit: Apparently I'm supposed to move the "responseG" variable and next line into the if statment. When I do that it doesnt activate, (using eclipse IDE, and it just appears as white and as an error) and tells me to delete else. https://gyazo.com/1a27fa9ab8802d594cccb35ecc0cb663 picture of what happens. furthermore if i try to use an else if statment it also says to delete it
Hi, welcome to Stackoverflow!
Your program will only ask for another input from your keyboard if you don't type "hello" or "Hello", or "hey", you know what I mean. If you type "hello" then it will print a line with
"Oh, well aren't you well-mannered. Hello there, how are you?"
And the program will be terminated...
That's what your code it's telling your program to do, since you are only asking for another input in the else statement's body.
As I can see you don't want to use a for loop, since you seem to only care about a path that says hi... how are you?... good... glad to hear... but if you care for it, you can use a while() statement or a do..while() or a for() to make it save in the variable many responses with the scr.nextLine(); function (it is a function), in that case you have to define when/how the program is going to stop asking for input and will terminate.
I believe this is what does what you were trying to do, with the proper indentation, and not declaring unnecessary variables:
public class Practice01{
public static void main (String[] args){
System.out.println("Hi there");
Scanner scr = new Scanner(System.in);
String response = scr.nextLine();
if (response.equalsIgnoreCase("hello") || response.equalsIgnoreCase("hi") || response.equalsIgnoreCase("hey")) {
System.out.println("Oh, well arent you well-mannered. Hello there, how are you?");
}
else {
System.out.println("Invalid Input");
}
//You don't need ResponseG... you've already created the response variable
response = scr.nextLine();
if (response.equalsIgnoreCase("good")) {
System.out.println("Glad to hear");
}
else {
System.out.println("Invalid Input");
}
}
}
You have to use a loop to keep the program working. After you get "Oh, well aren't you well-mannered. Hello there, how are you?" printed, it terminates the fact that there is no more tasks to do.
So what you want to do is move the ResponseG if statement into the your response if statement as that is stopping the code from complete since you are putting in the correct inputs. Also for future projects, to be more organized create variables at the beginning of the code.
public class Practice01{
public static void main (String[] args){
System.out.println("Hi there");
String responseG;
Scanner scr = new Scanner(System.in);
String response = scr.nextLine();
if (response.equalsIgnoreCase("hello") ||
response.equalsIgnoreCase("hi") ||
response.equalsIgnoreCase("hey")) {
System.out.println("Oh, well arent you well-mannered. Hello there, how are you?");
responseG = scr.nextLine();
if (responseG.equalsIgnoreCase("good")) {
System.out.println("Glad to hear");
}
} else {
System.out.println("Invalid Input");
}
}
}

How can I replace / edit only a specific word in Java?

I want a specific word being replaced/ edited. But unfortunately, other words are replaced too who contain the word to be replaced.
Example:
String test = "I am a ool tool";
Now if I want to replace the word "ool" with something, "tool" is gonna be changed as well. So how can I solve this problem? I JUST want ool to be edited. "tool" should stay like it is.
Here some code:
public class StringMethoden {
public static void main(String[] args) {
String bsp = "I am a ool tool";
if (bsp.matches("(.*)ool(.*)")){
bsp = bsp.replaceAll("ool", "test");
System.out.println(bsp);
}
else {
System.out.println("sentence does not conain 'ool' !");
}}
Outut: I am a test ttest
Word boundaries (\b) in Java RegEx make sure a certain point in the string is the start/end of a word.
bsp = bsp.replaceAll("\\bool\\b", "test");
Here is a similar approach for the issue, we can also use .contains() method in the following manner, feel free to ask questions if any.
String bsp = "I am a ool tool";
if (bsp.contains(" ool")) {
bsp = bsp.replaceAll(" ool", " test");
System.out.println(bsp);
} else {
System.out.println("sentence does not conain 'ool' !");
}
Output:
I am a test tool

Profanity filter

So far I have been able to censor "cat", "dog" and "llama". Now I just need to make the exception of "Dogmatic" but cannot figure it out for the life of me. Below I have attached what I have so far. Please any suggestions will help really.
/* take userinput and determine if it contains profanity
* if userinput contains profanity, it will be filtered
* and a new sentence will be generated with the word censored
*/
keyboard = new Scanner(System.in);
System.out.println("Welcome to the Star Bulletin Board!");
System.out.println("Generate your first post below!");
String userInput = keyboard.nextLine();
userInput = userInput.toLowerCase();
if (userInput.indexOf("cat") != 15){
System.out.println("Your post contains profanity.");
System.out.println("I have altered your post to appear as: ");
System.out.println(userInput.replaceAll("cat", "***"));
}
else
System.out.println(userInput);
if (userInput.indexOf("dog") != -1){
System.out.println("Your post contains profanity.");
System.out.println("I have altered your post to appear as: ");
System.out.println(userInput.replaceAll("dog", "***"));
}
if (userInput.indexOf("llama")!= -1){
System.out.println("Your post contains profanity.");
System.out.println("I have altered your post to appear as: ");
System.out.println(userInput.replaceAll("llama", "*****"));
}
You can use a word boundary \\b. Word boundaries match the edges of a word, like spaces or punctuation.
if (userInput.matches(".*\\bdog\\b.*")) {
userInput = userInput.replaceAll("\\bdog\\b", "***");
}
This will censor "Don't be a llama." but it won't censor "Don't be dogmatic."
userInput.matches(".*\\bdog\\b.*") is a slightly better condition than indexOf/contains because it has the same match as the replacement. indexOf/contains would still show the message despite not censoring anything. .* matches any character (except typically new lines), optionally.
Note: this is still not a very effective way to filter profanity. See http://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/.
Use word boundaries. Take a look at the following code; it will print true for all cases except the last one:
String a = "what you there";
String b = "yes what there";
String c = "yes there what";
String d = "whatabout this";
System.out.println(Pattern.compile("\\bwhat\\b").matcher(a).find());
System.out.println(Pattern.compile("\\bwhat\\b").matcher(b).find());
System.out.println(Pattern.compile("\\bwhat\\b").matcher(c).find());
System.out.println(Pattern.compile("\\bwhat\\b").matcher(d).find());
You can combine all your bad words into a single regex like so:
Pattern filter = Pattern.compile("\\b(cat|llama|dog)\\b");
This is fine for simple cases, but for a more robust solution you probably want to use a library. Take a look at this question for more information.

Replace one word from user input

For a project, I need to take a user input such as "I hate you" and I need to replace the word "hate" with "love". I can't use replace all.
I understand that I can use .indexOf and find the position of the word hate and then use concatenation to form a new sentence I'm just really confused on how to do that.
I'll show what I have below. Also can you guys keep in mind that I'm new to this site and programming. I'm not just here for a quick fix, I'm actually trying to learn this. I've been doing a lot of research and I can't seem to find an answer.
import java.util.Scanner;
public class ReplaceLab {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a line of text:");
String userInput = input.nextLine();
int position = userInput.indexOf("hello");
System.out.println("I have rephrased that line to read");
}
}
String.replace() will replace every ocurrance in your input String:
String userInput = input.nextLine();
String replaced = userInput.replace("hate", "love");// Here you have your new string
For example, "I hate to hate you" will become "I love to love you".
If only the first occurrence must be changed (making my example "I hate to love you") then alfasin comment is correct and String.replaceFirst() will get the job done.
If you have to use .indexOf()
String find = "hate";
String replace = "love";
int pos = userInput.indexOf(find);
int pos2 = pos + find.size();
String replaced = userInput.substring(0, pos) + " " + replace + " " + userInput.substring(pos2);
If you are doing this make sure to check that indexOf returns a valid number.

Output from while loop not working

Apologies for posting about this topic twice today, this one is a different question. So I am working on a java problem at the moment where I am creating a program that simulates the old TV quiz show, You Bet Your Life. The game show host, Groucho Marx, chooses a secret word, then chats with the contestants for a while. If either contestant uses the secret word in a sentence, he or she wins $100.00.
My program is meant to check for this secret word.
Here is my code:
import java.util.Scanner;
public class Groucho{
String secret;
Groucho(String secret){
this.secret = secret;
}
public boolean saysSecret(String line){
if(secret.equals(line)){
return(true);
}
else{
return(false);
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String line = in.nextLine();
Groucho g = new Groucho(line);
while (in.hasNextLine()) {
String guess = in.nextLine();
/*Not sure about these next two lines:
*String answer = g.saysSecret(guess);
*/System.out.println(answer);
}
}
}
When I run it nothing happens. I thought it should be returning true or false? What I would actually like it to do is if the line contains the secret word, it prints a message that says “You have won $100” and tells what the secret word is. Could anyone point me in the right direction?
Many thanks
Miles
As Sotirios points out, you should use saysSecret(String) to check if the guess is correct.
So the loop could look like:
while (in.hasNextLine()) {
String guess = in.nextLine();
if (g.saysSecret(guess))
{
System.out.println("You got it! The word was: "+g.secret);
} else {
System.out.println("Aw, try again.");
}
}
Your code does not work because you are assigning a boolean value to a String. You should compare the return value of g.saysSecret(guess), and then if this value is true print your successful message (or even print a failure message if this value is false).
Also, you have said:
What I would actually like it to do is if the line contains the secret word ...
so
secret.equals(line)
is not what you want since that will be true only if the entire line is equal to the secret word. For search for a word inside a line you could use:
line.contains(secret)
or maybe you need a more elaborated method for case insensitive matchs and so on.

Categories

Resources