I have seen similar questions to this problem and the answer on the Stack Overflow did not seem to satisfy the problem. I heard that you need to use use.Delimeter, however, I never used it before and want to know how to use it to exclude punctuation from a string that the user inputs. The assignment prompt question is here:
Change the CountWords program (Listing 3.10) so that it does not include punctuation characters in its character count. Hint: You must change the set of delimiters used by the StringTokenizer class.
Here is Listing 3.10:
import java.util.Scanner;
import java.util.StringTokenizer;
public class ThreeEight {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int wordCount = 0, characterCount = 0;
String line, word;
StringTokenizer tokenizer;
System.out.println("Please enter text (type DONE to quit):");
line = scan.next();
while (!line.equals("DONE")) {
tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word = tokenizer.nextToken();
wordCount++;
characterCount += word.length();
}
line = scan.next();
}
System.out.println("Number of words: " + wordCount);
System.out.println("Number of characters: " + characterCount);
}
}
Output:
Please enter text (type DONE to quit):
Hello World! ##$%^&():"<>?~/\
DONE
Number of words: 3
Number of characters: 29
As you can see, it does not count punctuation, what code would I use to exclude the punctuation? I used use.Delimeter but it said that it was an invalid method.
Related
I am somewhat lost on what to do.
There are 4 parts.
Prompt the user for a string that contains two strings separated by a comma.
Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.
Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings.
Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit.
Final outcome should print out as follows:
Enter input string: Jill, Allen
First word: Jill
Second word: Allen
Enter input string: Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string: Washington,DC
First word: Washington
Second word: DC
Enter input string: q
I've figured out everything out but can't figure out the second part. I don't exactly know how to do the code for does not contain comma.
Here's my code:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String lineString = "";
int commaLocation = 0;
String firstWord = "";
String secondWord = "";
boolean inputDone = false;
while (!inputDone) {
System.out.println("Enter input string: ");
lineString = scnr.nextLine();
if (lineString.equals("q")) {
inputDone = true;
}
else {
commaLocation = lineString.indexOf(',');
firstWord = lineString.substring(0, commaLocation);
secondWord = lineString.substring(commaLocation + 1, lineString.length());
System.out.println("First word: " + firstWord);
System.out.println("Second word:" + secondWord);
System.out.println();
System.out.println();
}
}
return;
}
}
Let's have a look at the line:
commaLocation = lineString.indexOf(',');
in case there is no comma, .indexOf() returns -1 - you can take advantage of it and add an if condition right after this line and handle this case as well!
You can use :
if (input.matches("[^,]+,[^,]+")) {//If the input match two strings separated by a comma
//split using this regex \s*,\s* zero or more spaces separated by comman
String[] results = input.split("\\s*,\\s*");
System.out.println("First word: " + results[0]);
System.out.println("Second word: " + results[1]);
} else {
//error, there are no two strings separated by a comma
}
I am trying to figure out how to place a limit on the amount of characters used in a String but, I can't seem to figure out how to code that if, for example I say 'He' instead of 'Hello' I want my code to show an error because 'He' contains less than 3 characters. Any suggestions?
package trial;
import java.util.Scanner;
public class Trial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = input.nextLine();
System.out.println("The Word you have typed is: " + word);
your code is good just let the user keep entering the value until the characters more than 3 so you do that by while loop that check the number of word's characters
package trial;
import java.util.Scanner;
public class Trial {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word="";
while(word.length()<3){
System.out.println("Enter a word with more or equals to 3 characters: ");
word = input.nextLine();
}
System.out.println("The Word you have typed is: " + word);
If you want to allow only alphanumeric characters you can use a regex with \w and leverage String.matches like:
String word = input.nextLine();
// Validates word is 3 or more characters long
if (!word.matches("\\w{3,}")) {
throw new IllegalArgumentException("Word must have 3 or more characters");
}
System.out.println("The Word you have typed is: " + word);
Another regex ideas might be:
[\w\s]{3,} --> alphanumeric and spaces with 3 or more
You can check the Strings length to see if it is less than 3...
if(word.length() < 3)
{
System.err.println("Error");
}
import java.util.*;
public class VowelCounter
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Input a series of characters: ");
String letters = keyboard.next();
int count = 0;
for (int i = 0; i < letters.length(); i++)
{
char characters = letters.charAt(i);
if (isVowel(characters) == true)
{
count++;
}
}
System.out.println("The number of vowels is: " + count);
}
public static boolean isVowel(char characters)
{
boolean result;
if(characters=='a' || characters=='e' || characters=='i' || characters=='o' || characters=='u')
result = true;
else
result = false;
return result;
}
}
The code works but im suppose to input "Spring break only comes once a year." which if i do with the spaces my program will only find the vowels of Spring. how do i make it so it will skip the spaces and read the whole sentence.
This is your problem:
String letters = keyboard.next();
It has nothing to do with the vowel-counting part - but everything to do with reading the value. The Scanner.next() method will only read to the end of the token - which means it stops on whitespace, by default.
Change that to
String letters = keyboard.nextLine();
and you should be fine.
You should verify this is the problem by printing out the string you're working with, e.g.
System.out.println("Counting vowels in: " + letters);
When you do:
String letters = keyboard.next();
The Scanner stops reading at the first whitespace.
To read the complete phrase until you press enter, you should use nextLine() instead:
String letters = keyboard.nextLine();
Just use
String letters = keyboard.nextLine();
instead of
String letters = keyboard.next();
This is because .nextLine() will read line by line so that you can have your complete statement in latters. Hope this will help you
I am writing a simple code that takes an input read by the scanner and saved into a variable word.
It is required for an assignment to create a separate method that will take that string and convert all the letters to a '?' mark. At the spaces, however, there should be a space.
The problem is that every time I run this code, it stops at the space.
Here is my code:
import java.util.Scanner;
public class commonPhrase {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String word;
System.out.print("Welcome to the Guessing Game.");
System.out.println("");
System.out.println("Please enter a common phrase");
word = input.next();
createTemplate(word);
}
public static String createTemplate(String word) {
String sPhrase = "";
for (int i=0; i < word.length(); i++) {
if (word.charAt(i) == ' '){
sPhrase += " ";
}
else {
sPhrase += "?";
}
}
System.out.println(sPhrase);
return sPhrase;
}
}
And here is a sample run of it:
Welcome to the Guessing Game.
Please enter a common phrase.
Why wont it add spaces!!!!!!!
???
You call next() on the Scanner, but that method grabs the next token, and by default it's separating tokens by whitespace. You only gathered one word.
Call nextLine() instead, to grab the text of the entire line.
word = input.nextLine();
Sample run with fix above:
Welcome to the Guessing Game.
Please enter a common phrase
Stack Overflow
????? ????????
I need to write for loop to iterate through a String object (nested within a String[] array) to operate on each character within this string with the following criteria.
first, add a hyphen to the string
if the character is not a vowel, add this character to the end of the string, and then remove it from the beginning of the string.
if the character is a vowel, then add "v" to the end of the string.
Every time I have attempted this with various loops and various strategies/implementations, I have somehow ended up with the StringIndexOutOfBoundsException error.
Any ideas?
Update: Here is all of the code. I did not need help with the rest of the program, simply this part. However, I understand that you have to see the system at work.
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class plT
{
public static void main(String[] args) throws IOException
{
String file = "";
String line = "";
String[] tempString;
String transWord = ""; // final String for output
int wordTranslatedCount = 0;
int sentenceTranslatedCount = 0;
Scanner stdin = new Scanner(System.in);
System.out.println("Welcome to the Pig-Latin translator!");
System.out.println("Please enter the file name with the sentences you wish to translate");
file = stdin.nextLine();
Scanner fileScanner = new Scanner(new File(file));
fileScanner.nextLine();
while (fileScanner.hasNextLine())
{
line = fileScanner.nextLine();
tempString = line.split(" ");
for (String words : tempString)
{
if(isVowel(words.charAt(0)) || Character.isDigit(words.charAt(0)))
{
transWord += words + "-way ";
transWord.trim();
wordTranslatedCount++;
}
else
{
transWord += "-";
// for(int i = 0; i < words.length(); i++)
transWord += words.substring(1, words.length()) + "-" + words.charAt(0) + "ay ";
transWord.trim();
wordTranslatedCount++;
}
}
System.out.println("\'" + line + "\' in Pig-Latin is");
System.out.println("\t" + transWord);
transWord = "";
System.out.println();
sentenceTranslatedCount++;
}
System.out.println("Total number of sentences translated: " + sentenceTranslatedCount);
System.out.println("Total number of words translated: " + wordTranslatedCount);
fileScanner.close();
stdin.close();
}
public static boolean isVowel (char c)
{
return "AEIOUYaeiouy".indexOf(c) != -1;
}
}
Also, here is the example file from which text is being pulled (we are skipping the first line):
2
How are you today
This example has numbers 1234
Assuming that the issue is StringIndexOutOfBoundsException, then the only way this is going to occur, is when one of the words is an empty String. Knowing this also provides the solution: do something different (if \ else) when words is of length zero to handle the special case differently. This is one way to do this:
if (!"".equals(words)) {
// your logic goes here
}
another way, is to simply do this inside the loop (when you have a loop):
if ("".equals(words)) continue;
// Then rest of your logic goes here
If that is not the case or the issue, then the clue is in the parts of the code you are not showing us (you didn't give us the relevant code after all in that case). Better provide a complete subset of the code that can be used to replicate the problem (testcase), and the complete exception (so we don't even have to try it out ourselves.