Profanity Test Not Working As Expected (In Chat Application)? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to create a profanity test for my app, but it seems to malfunction!! why?
code:
public boolean filter(String message)
{
String[] words={*CUSS WORDS*};
for(int i=0; i< (words.length-1); i++ )
{
if(message.indexOf(words[i].toLowerCase())!= -1)
{
return true;
}
}
return false;
}
OR Another code (BUT SAME FUNCTION):
public boolean filter(String message)
{
String[] words={CUSS WORDS};
for(int i=0; i< (words.length-1); i++ )
{
if(message.contains(words[i}))
{
return true;
}
}
return false;
}
So the PROBLEM IS:
I tried these 2 pieces of codes with similar results. For example for "Fuck", if I enter "fu" into my app it stops it from being entered or for "ass", if I enter "as" it stop it from being entered! (Filter works to stop any profanity from entering the chat)

Store your curse words in a set, then break up the users sentence into individual words. Check each word to see if it's in your set of curse words.
public boolean curse(String str){
//Create your set here
HashSet<String> wordSet = new HashSet<String>();
//Use it's add function to add your curse words
wordSet.add("ass");
String array[] = str.split(" ");
for(String s : array){
if(wordSet.contains(s.toLowerCase()))
return true;
}
return false;
}

I can't comment because of my reputation, but, continuing Elroy Jetson's answer, you initialize the HashSet using Arrays.asList, as is described here in this answer: https://stackoverflow.com/a/16194967/2836264. The HashMap constructor takes in this case a List<String>, that is created from the String[].
String[] cussArray = {"fuck", "shit", "brocolli"};
HashSet<String> cussSet = new HashSet<>(Arrays.asList(cussArray));

Related

String index out of range even though the string is limited [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am a student and I am learning Java.I recently got a question which said I had to find the largest word in a given string..I wrote a code but it is giving me an error that string index is out of bounds even though I limited it to the length of the string..Can someone help me with the code..Please use simple language(I am not an expert)
Code
import java.util.*;
class word
{
void def()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String s1=sc.nextLine();
int length=s1.length();
length++; //My name
int j=0; //0123456
int word=0;
int findex=0;
int lindex=0;
int lword=0;
for(int i=0;i<length;i++)
{
if(s1.charAt(i)==' ' && j==0)
{
lword=i;
findex=0;
lindex=i;
j=i;
}
else if(s1.charAt(i)==' ')
{
if(i-j-1>lword)
{
findex=j;
lindex=i;
lword=i-j-1;
}
j=i;
}
else if(i==length-1)
{
if(i-j-1>lword)
{
findex=j;
lindex=i;
}
}
}
System.out.println("Largest word is:"+s1.substring(findex,lindex+1));
}
}
By doing length++ you make sure that your length variable will be larger then the actual string length. at the last loop step there will be no char at s1.charAt(i)
Just remove the line with length++

Shorter way to do this challenge? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Basically, I am getting ready for an interview and following a regime that gives me a bunch of challenges that are often thrown in interviews.
This particular challenge's goal is to count the number of words that appear more than once in a sentence excluding punctuations. I did it but it took me at least 5 minutes to come up with it and code it.
I'm not sure if taking 5 minutes is acceptable to code something like this in java interviews so I would like to see something simpler with maybe less code. Below is how I solved it.
System.out.println("Part 6 challenge-------------------------------------------------------------------------");
String sentence3 = "She's the queen and likes, apples APPLES, bananas BANANAS Bananas, and oranges ORANGE."; //original string
StringBuilder sb3 = new StringBuilder(); //declared string builder to build new string without punctuations
char [] punctuations = {'.',',',':','?','!',';'};//Char array containing punctuations to lookout for
for (int i=0; i<sentence3.length(); i++){
boolean p = false; //declared boolean within loop to turn on if punctuation was found in the original string
for (Character c: punctuations){
if (sentence3.charAt(i) == c){
p = true;// turn on
}
} if(!p){
sb3.append(sentence3.charAt(i));//if no punctuations found, add it to the string builder to build new string
}
}
String word[] = sb3.toString().split(" ");
Set<String> uniqueWords = new HashSet<>();
int count = 0;
for (String s: word) {
uniqueWords.add(s.toLowerCase());
}
for (String s: uniqueWords){
for (String w: word){
if (s.equals(w.toLowerCase())){
count++;
}
}
System.out.println(String.format("Found %s %d times", s, count));
count =0;
}
A shorter way, outlined:
Split by regexp;
Filter for words (may be not needed depending on your regexp);
Replace Set<String> with a Map<String, Integer> and count word quantities in linear time;
Filter out and output words with count > 1.
BTW this can all be one stream expression if you're into minimal statement count.

trying to print out the array in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
System.out.println("Please input the elements and seperate each by a comma.");
e = dk.nextLine();
String[] elems = new String[e.length()];
st = new StringTokenizer(e,",");
for (int i = 0; i<e.length(); i++) {
elems[i] = st.nextToken().toString();
}
for (int i=0; i<e.length(); i++){
System.out.println(elems[i]);
}
I am trying to print out the array elems[] but it wont work the error java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(StringTokenizer.java:349 seems to be at line:
elems[i] = st.nextToken().toString();
can you help me identify and understand the problem?
A correct version:
String[] elems = e.split(",");
for(String elem : elems) {
System.out.println(elem);
}
The mistake you made is that e.length() returns the size of the string (its number of characters) so you ended up calling st.nextToken() more times than there are actual tokens separated by ",". Hence the exception.
#Jean posted a slim version of what you are trying, but ultimately to help to understand the error
e = dk.nextLine(); // input: Alfredo,Bauer,Cisco
String[] elems = new String[e.length()]; // length is 20
st = new StringTokenizer(e,","); // st has a length of 3
Now if you call it like this
for(int i = 0;i<e.length();i++){
elems[i] = st.nextToken().toString(); // NoSuchElementException
}
Because you try to call the nextToken() which does not exist.
The docs:
Returns the next token from this string tokenizer.
Throws:
NoSuchElementException - if there are no more tokens in this
tokenizer's string.
To fix your problem use the length of countTokens()
OR
while(st.hasMoreElements()){
elems[i] = st.nextToken().toString();
}
Another alternative.
String[] elems = e.split(",");
System.out.print(Arrays.toString(elems ));

Break from a loop when a condition is true [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this:
for(String s : names){ //names is an ArrayList of strings
if( s.equals("bob") ){
//do sth and then break from the loop
break;
}
}
When the condition inside the if is true, I would expect the for-loop to break. But it doesn't.. what I code wrong?
EDIT:
the problem was that I have an extra for loop in my code
for( //a loop here){
for(String s : names){ //names is an ArrayList of strings
if( s.equals("bob") ){
//do sth and then break from the loop
break;
}
}
}
that's why the inside loop was executing after the break...
Code looks fine, there is some data issue in your list or difference of case in two strings . Try using equalsIgnoreCase instead of equals as suggested
It just prints hi, as soon as bob comes it breaks.
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
names.add("hi");
names.add("bob");
names.add("bye");
for (String s : names) {
if (s.equals("bob")) {
System.out.println("breaking...");
break;
} else {
System.out.println(s);
}
}
}
output
hi
breaking...

Read first 100 string array, java i/o [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I was directed from to this website from a friend. The goal is to read the first 100 strings in the txt file and count how many times those words appear and print them off.
Thank you so much in advance. I've done very well with code but this has stumped me for some reason.
import java.util.Arrays;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Program6 {
public static void main(String[] args) throws FileNotFoundException {
WordAnalysis a = new WordAnalysis();
a.ReadFile();
}}
class WordAnalysis{
String[] coun = new String[1000];
int[] ana = new int[100];
void ReadFile() throws FileNotFoundException {
Scanner read = new Scanner(new File("myths.txt"));
int[] ana = new int[100];
String coun = new String();
String word=null;
while(read.hasNext()) {
word = read.next();
String[] arrWord = word.split(" ");
}
}
}
Procedure:
1: Read lines [0,99] via nextLine() from Scanner
2: Split up line with another Scanner and use next() to get each word. Alternatively, you can use split.
3: Put each word in a HashMap(String, Integer) where String is the word, and Integer is the number of times it has appeared
4: Iterate through HashMap and prints out key, value pairs
Check this, here I've used a map to keep word count.
int count = 0;
HashMap<String, Integer> wordCntMap = new HashMap();
while (read.hasNext()) {
count++;
word = read.next();
String[] arrWord = word.split(" ");
if (count == 100) {
break;
}
for (String str : arrWord) {
Integer num = wordCntMap.get(str);
if (num == null) {
wordCntMap.put(str, new Integer(1));
} else {
wordCntMap.put(str, num + 1);
}
}
}
System.out.println("Word Count " + wordCntMap);
Welcome to Stack Overflow, where no answer is too stupid and no comment too thoughtless.
It seems fairly clear however that you haven't finished writing this code. :-)
Now that you have your words in arrWord, you need to start using some sort of structure that will allow you to keep track of each word and how many times its been seen.
There are plenty of containers that let you use a string as a key and an integer as a value. For your purposes it doesn't matter which one you use.
For each word in arrWord, see if you can find it in your structure (Dictionary, Hashmap, whatever). If you can't find 'word', insert a new entry of [word, 1]. If you can find 'word' then increment the counter that you find.
When you are done, all you need to do is print out the key-value pair for each entry in your structure.
HTH!

Categories

Resources