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.
Related
How do I print only the first letter of the first word and the whole word of the last? for example,
I will request username input like "Enter your first and last name" and then if I type my name like "Peter Griffin", I want to print only "P and Griffin". I hope this question make sense. Please, help. I'm a complete beginner as you can tell.
Here is my code:
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter your first and last name");
String fname=scan.next();
}
The String methods trim, substring, indexof, lastindexof, and maybe split should get you going.
This should do the work (typed directly here, so syntax errors might be there)
String fname=scan.nextLine(); // or however you would read whole line
String parts=fname.split(" ");
System.out.printf("%s %s",parts[0].substring(0,1),parts[parts.length-1]);
What you have to do next:
Check if there actually at least 2 elements in parts array
Check if first element is actually at least 1 char (no empty parts)
Check if there is actually line to read
Do your next homework yourself, otherwise you will not anything
I recommand you to watch subString(1, x) and indexOf(" ") to cut from index 1 to first space.
or here a other exemple, dealing with lower and multi name :
String s = "peter griffin foobar";
String[] splitted = s.toLowerCase().split(" ");
StringBuilder results = new StringBuilder();
results.append(String.valueOf(splitted[0].charAt(0)).toUpperCase() + " ");
for (int i = 1; i < splitted.length; i++) {
results.append(splitted[i].substring(0, 1).toUpperCase() + splitted[i].substring(1)+" ");
}
System.out.println(results.toString());
I'm not sure where I am going wrong with this particular code. Could someone please lend me some guidance to this?
Here is my question as well as what I have attempted to have as an outcome.
Modify songVerse to play "The Name Game" (OxfordDictionaries.com), by replacing "(Name)" with userName but without the first letter.
Ex: If userName = "Katie" and songVerse = "Banana-fana fo-f(Name)!", the program prints:
Banana-fana fo-fatie!
Ex: If userName = "Katie" and songVerse = "Fee fi mo-m(Name)", the program prints:
Fee fi mo-matie
Note: You may assume songVerse will always contain the substring "(Name)".
Code that I tried this last time...and no matter what I put in I keep getting the same results. I've tried different scenarios of the "userName.substring()" and still have the same outcome.
import java.util.Scanner;
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse + userName.substring(1 , userName.length()); // this is where my problem is.
System.out.println(songVerse);
}
}
1 test passed
All tests passed
Run
Testing Katie and Banana-fana fo-f(Name)!
Output differs. See highlights below.
Your output
Banana-fana fo-f(Name)!tie
Expected output
Banana-fana fo-fatie!
Testing Walter and Banana-fana fo-f(Name)!
Output differs. See highlights below.
Your output
Banana-fana fo-f(Name)!lter
Expected output
Banana-fana fo-falter!
Testing Katie and Fee fi mo-m(Name)
Output differs. See highlights below.
Your output
Fee fi mo-m(Name)tie
Expected output
Fee fi mo-matie
Here you go.
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse.replace("(Name)", userName.substring(0));
System.out.println(songVerse);
}
}
here you removed first character already from userName, so at the second last line you again don't need to remove it.
and for the song Verse, you need to remove "(NAME)" from it, so here you can use
songVerse = songVerse.replace("(NAME)","");
songVerse = songVerse+userName;
The method substring(int begin, int end) let hoose/create a substring from the initial String indicating the numbers of chars from which the substring should begin and end or begin only. There are no other variants to edit a substring, while it will not become a part of a freshly made string (“String songVerse” in your case). The object.replace() method should change the indicated “Text” (in your case it’s a “(Name)”) onto anything that you’d like to be inserted instead of it independently on the quantity or type of the chars before or after the “Text”. The variant proposed by Nicholas K is correct and should work or you can try its shorter version, however the result will be the same:
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
songVerse = scnr.nextLine();
songVerse = songVerse.replace("(Name)", userName.substring(1));
System.out.println(songVerse);
}
}
The problem with your code is that you are not attempting to solve the problem that you described in your question.
Try following these steps:
Devise a list of steps written in English to solve the problem; pay attention to details.
Run the list of steps in step 1 by hand.
Convert the steps in step 1 to code.
Here are some hints:
You will be reading the lyrics one line at a time.
Some lines have a replacement and others do not.
You will receive the Name as input one time; generate the name replacement value one time and use it each time you perform a replacement.
Your code is terrible.
Here is some more about "Pay attention to details"
You do not have a loop in your code;
this will read one line of lyrics and perform one substitution.
Count the number of lines in the lyrics.
If the number of lines is greater than one,
then your technique is guaranteed to fail.
If you have a loop in your code but decided not to include it in your code,
stop lying in your questions.
We can not help you fix code that you pretend does not exist.
In a sane world,
the name to use for the substitutions will appear exactly one time.
Read it one time.
In order to replace (Name) in a string, you must first find (Name) in a string.
This is pretty easy
import java.util.Scanner;
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse.replace("(Name)", userName);
/* Your solution goes here */
System.out.println(songVerse);
}
}
I am in a beginners course but am having difficulty with the approach for the following question: Write a program that asks the user to enter a line of input. The program should then display a line containing only the even numbered words.
For example, if the user entered
I had a dream that Jake ate a blue frog,
The output should be
had dream Jake a frog
I am not sure what method to use to solve this. I began with the following, but I know that will simply return the entire input:
import java.util.Scanner;
public class HW2Q1
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence");
String sentence = keyboard.next();
System.out.println();
System.out.println(sentence);
}
}
I dont want to give away the answer to the question (for the test, not here), but I suggest you look into
String.Split()
From there you would need to iterate through the results and combine in another string for output. Hope that helps.
While there will be more simpler and easier way to do this, I'll use the basic structure- for loop, if block and a while loop to achieve it. I hope you will be able to crack the code. Try running it and let me know if there is an error.
String newsent;
int i;
//declare these 2 variables
sentence.trim(); //this is important as our program runs on space
for(i=0;i<sentence.length;i++) //to skip the odd words
{
if(sentence.charAt(i)=" " && sentence.charAt(i+1)!=" ") //enters when a space is encountered after every odd word
{
i++;
while(i<sentence.length && sentence.charAt(i)!=" ") //adds the even word to the string newsent letter by letter unless a space is encountered
{
newsent=newsent + sentence.charAt(i);
i++;
}
newsent=newsent+" "; //add space at the end of even word added to the newsent
}
}
System.out.println(newsent.trim());
// removes the extra space at the end and prints newsent
you should use sentence.split(regex) the regular expression is going to describe what separate your worlds , in your case it is white space (' ') so the regex is going to be like this:
regex="[ ]+";
the [ ] means that a space will separate your words the + means that it can be a single or multiple successive white space (ie one space or more)
your code might look like this
Scanner sc= new Scanner(System.in);
String line=sc.nextLine();
String[] chunks=line.split("[ ]+");
String finalresult="";
int l=chunks.length/2;
for(int i=0;i<=l;i++){
finalresult+=chunks[i*2]+" ";//means finalresult= finalresult+chunks[i*2]+" "
}
System.out.println(finalresult);
Since you said you are a beginner, I'm going to try and use simple methods.
You could use the indexOf() method to find the indices of spaces. Then, using a while loop for the length of the sentence, go through the sentence adding every even word. To determine an even word, create an integer and add 1 to it for every iteration of the while loop. Use (integer you made)%2==0 to determine whether you are on an even or odd iteration. Concatenate the word on every even iteration (using an if statement).
If you get something like Index out of range -1, manipulate the input string by adding a space to the end.
Remember to structure the loop such that, regardless of the whether it is an even or odd iteration, the counter increases by 1.
You could alternatively remove the odd words instead of concatenation the even words, but that would be more difficult.
Not sure how you want to handle things like multiple spaces between words or weird non-alphabetically characters in the entry but this should take care of the main use case:
import java.util.Scanner;
public class HW2Q1 {
public static void main(String[] args)
{
System.out.println("Enter a sentence");
// get input and convert it to a list
Scanner keyboard = new Scanner(System.in);
String sentence = keyboard.nextLine();
String[] sentenceList = sentence.split(" ");
// iterate through the list and write elements with odd indices to a String
String returnVal = new String();
for (int i = 1; i < sentenceList.length; i+=2) {
returnVal += sentenceList[i] + " ";
}
// print the string to the console, and remove trailing whitespace.
System.out.println(returnVal.trim());
}
}
Edit Thanks for the help guys got it working now.
So I had a question to do to ask a user for first name and last name which I have done no problem but then I thought it's be good to expand the program so that if someone entered a surname like McCabe it would print T McC instead of TM. I'm just not sure about how to compare the first two letters of the secondname string to see if they are "mc".
public class InitialsAlt {
public static void main(String [] args){
Scanner keyboardIn = new Scanner (System.in);
String firstname = new String();
System.out.print (" Enter your first name ");
firstname = keyboardIn.nextLine();
String secondname = new String();
System.out.print (" Enter your second name ");
secondname = keyboardIn.nextLine();
if(secondname.charAt(0, 1)== "mc" ) {
System.out.print("Your initals are " + firstname.charAt(0)+ secondname.charAt(0,1,2));
}
else {
System.out.print("Your initals are " + firstname.charAt(0)+ secondname.charAt(0));
}
}
}
if (secondName.toLowerCase().startsWith("mc")) {
The easiest way is to use String.startsWith:
yourString.toLowerCase().startsWith("mc")
If you want to avoid lowercasing the entire string or creating a new object, only to check the first two characters:
yourString.length() >= 2
&& Character.toLowerCase(yourString.charAt(0)) == 'm'
&& Character.toLowerCase(yourString.charAt(1)) == 'c'
However, I would use the former solution as it is far more readable, and the performance hit from lowercasing the entire string is almost certainly negligible, unless you are doing this on quite large strings.
Use yourString.toLowerCase().indexOf("mc")==0. This will involve creation of a new String only once (Since indexOf() doesn't create a new one, using indexOf() would be better than using subString() here)
Use substring to get the first two letters, then convert to lowercase, then check to see if it equals:
String someString = "McElroy";
if (someString.subString(0,2).toLowerCase().equals("mc")) {
//do something
}
If its case insensitive you could use the Apache Commons Lang library:
if(StringUtils.startsWithIgnoreCase(secondname, "mc") {
// Do nice stuff
}
Otherwise, you can use:
if(StringUtils.startsWith(secondname.toLowerCase(), "mc") {
// Do nice stuff
}
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.