0

I am attempting to split a word from its punctuation:

So for example if the word is "Hello?". I want to store "Hello" in one variable and the "?" in another variable.

Here is my code so far:

    String inWord = "hello?";
    if (inWord.contains(","+"?"+"."+"!"+";")) {

        String parts[] = inWord.split("\\," + "\\?" + "\\." + "\\!" + "\\;");
        String word = parts[0];
        String punctuation = parts[1];
    } else {
        String word = inWord;
    }

    System.out.println(word);
    System.out.println(punctuation);

My problem is that I am getting error: cannot find symbol when I try and print out the word and the punctuation.

Thanks for help in advance

user130316
  • 29
  • 7
  • 2
    You understand that [`+` != `or`]? – Rohit Jain Mar 29 '14 at 12:22
  • 1
    The scope of a variable declaration like `String word = ...` is only the block (the pieces of code inside '{' and '}') that it's in. The variables `word` and `punctuation` don't exist in the scope in which you try to print them. – Erwin Bolwidt Mar 29 '14 at 12:23
  • Also you might better use String.matches instead String.contains – donfuxx Mar 29 '14 at 12:28
  • It is good practice on StackOverflow to also print your error message completely. Yours, as @ErwinBolwidt pointed out, would have been a compile error. This way the question can be found be the next person having the same error message. Chances are the cause of the error is also similar. – Patru Mar 29 '14 at 12:29
  • The `split` method deletes the delimiter, which means you wouldn't conserve the punctuation character http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String) – ArianJM Mar 29 '14 at 12:50

5 Answers5

0

There are other things wrong with your code but your question was why you get the 'cannot find symbol' error.

String inWord = "hello?";
String word;
String punctuation = null;
if (inWord.contains(","+"?"+"."+"!"+";")) {
    String parts[] = inWord.split("\\," + "\\?" + "\\." + "\\!" + "\\;");
    word = parts[0];
    punctuation = parts[1];
} else {
    word = inWord;
}

System.out.println(word);
System.out.println(punctuation);

The scope of a variable declaration like String word = ... is only the block (the pieces of code inside '{' and '}') that it's in. The variables word and punctuation don't exist in the scope in which you try to print them.

You need to declare your variables word and punctuation in the same scope (or an enclosing scope) of where you access them in your System.out.println

Erwin Bolwidt
  • 28,093
  • 15
  • 46
  • 70
0

You could try with your custom contains function and StringTokenizer as:

    public class Test{

    public static void main(String[] args) {
        String inWord = "hello";
        String[] wordAndPunctuation = null;
        char[] punctuations =new char[]{',','?','.','!',';'};
        StringTokenizer tokenizer = new StringTokenizer(inWord,new String(punctuations),true);
        int i = 0;

        if (Test.contains(inWord,punctuations)) {
            while(tokenizer.hasMoreTokens()){
                wordAndPunctuation = new String[tokenizer.countTokens()];
                System.out.println(tokenizer.countTokens());
                wordAndPunctuation[i] = tokenizer.nextToken();
                i++;
            }
        }else{
            System.out.println("No punctuation in "+inWord);
        }
    }

    public static boolean contains(String str, char[] charArr){
        System.out.println(Arrays.toString(charArr));
        for(char c:charArr){
            if(str.contains(String.valueOf(c)))
            return true;
        }
        return false;
    }
}
Shekhar Khairnar
  • 2,453
  • 3
  • 22
  • 43
  • `StringTokenizer` is deprecated. See [this](http://stackoverflow.com/questions/691184/scanner-vs-stringtokenizer-vs-string-split). – Hungry Blue Dev Mar 31 '14 at 06:45
0

You made the following errors in your code.

1.Declare the string outside the if condition

2.inWord.contains(","+"?"+"."+"!"+";") this is equal to inword.contains(",?.!;") , so the condition will fail always and it goes to else condition

  1. split() will not store the value based on which you split the string

eg

 String string = "004-034556";

 String[] parts = string.split("-");

 String part1 = parts[0]; // 004

 String part2 = parts[1]; // 034556

In this the value "-" can't be stored.Hope you understand what i'm trying to convey.

0

I would recommend parsing through the String and checking if the character is a punctuation method:

String sentence = "Hello? Is this Mrs. Doubtfire?"; // Example.
ArrayList<String> chunks = new ArrayList<>();   // Will store the "non-punctuated chunks"
ArrayList<Character> puncts = new ArrayList<>();// Will the punctuations in the "sentence"
char[] punctuations = {',','?','.','!',';'};    // Store punctuations here.
int lastIndex = 0;
for (int i = 0; i < sentence.length(); i++) {
    char c = sentence.charAt(i);
    for (char punctuation : punctuations) {
        if (c == punctuation) {
            chunks.add(sentence.substring(lastIndex, i).trim());
            puncts.add(c);
            lastIndex = i + 1;
        }
    }
}
System.out.println(chunks);
System.out.println(puncts);

Output:

[Hello, Is this Mrs, Doubtfire]
[?, ., ?]

And remember to import java.util.ArrayList!

Hungry Blue Dev
  • 1,283
  • 15
  • 29
0

Why don't you do this:

String s = "hello!";

Pattern p = Pattern.compile("(\\w+)?(\\W)");
Matcher m = p.matcher(s);
while (m.find()) {
    System.out.println("Word: " + m.group(1) + " | Punctuation: " + m.group(2));
}

Group1 will contain the word and Group2 will contain the punctuation.

Demo : http://ideone.com/ljIZFW

Amit Joki
  • 53,955
  • 7
  • 67
  • 89