Char count of each token in Tokenized String, Java - java

I'm trying to figure out if I can count the characters of each token and display that information such as:
day is tokenized and my output would be: "Day has 3 characters." and continue to do that for each token.
My last loop to print out the # of characters in each token never prints:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
Example of Console:
Please type a sentence containing at least 4 words, with a maximum of 8 words:
Hello there this is a test
Thank you.
You entered:
Hello there this is a test
Each word in your sentence is: [Hello, there, this, is, a, test]

First off, I have added the necessary imports and built a class around this main method. This should compile.
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class SOQ_20200913_1
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
Next, let's look at this working example. It seems like everything up until your final while loop (the one that counts character length) works just fine. But if you notice, the while loop before the final one will continue looping until it has no more tokens to fetch. So, after it has finished gathering all of the tokens and has no more tokens to gather, you try and create the final while loop, asking it to gather more tokens. It would not have reached the while loop until it ran out of tokens to gather!
Finally, in order to solve this, you can simply go through the list that you added to in the second to last while loop, and simply cycle through that for your final loop!
For example:
int totalLength = 0;
for (String each : tokenizedInput) {
totalLength += each.length();
System.out.println("Word: " + each + " Length:" + each.length());
}

Related

How do I print a letter based on the index of the string?

I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.

program won't loop after first user input

I have been trying to write this code where a user enters two words with or without a comma and if it does not have a comma print the an error saying so and then loop back to ask for another set of words. Yes this is homework and I have searched the internet for help and it just has not clicked with me so far. I am needing help with the loop in my code which is java. These are the set of requirements for my warm up program followed by my code. Thank you for any help anyone can give.
1) Prompt the user for a string that contains two strings separated by a comma.
2) Report an error if the input string does not contain a comma.
3) Extract the two words from the input string and remove any spaces. Store the
strings in two separate variables and output the strings.
4) Using a loop, extend the program to handle multiple lines of input. Continue
until the user enters q to quit.
Here is my code:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Scanner inSS = null;
String lineString = "";
String firstWord = "";
String secondWord = "";
boolean inputDone = false;
System.out.println("Enter input string: ");
while (!inputDone) {
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
if (firstWord.equals("q")) {
System.out.println("Exiting.");
inputDone = true;
}
if (lineString.contains(",")) {
String[] parts = lineString.trim().split("\\s*,\\s*");
firstWord = parts[0];
secondWord = parts[1];
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
} else {
System.out.println("Error: No comma in string");
}
break;
}
return;
}
}
1) You do not need the return statement for a main method of type void
2) The break at the end of your loop is what is terminating it after the first run.
Writing break; within your loop is the same thing as telling your loop to stop looping. If you want to define another condition to terminate your loop, but dont want to put it in your while, then put your break inside of some sort of condition, that way it doesn't happen every single time.
I am trying to figure out when the user enters q the program quits here is my code so far.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
String s = sc.nextLine();
System.out.println("Enter input string: ");
if (s.indexOf(",") == -1) //checks if there is a comma in the string
{
System.out.println("Error: No comma in string");
} else {
//there is a comma in the string
String s1 = s.substring(0, s.indexOf(","));
String s2 = s.substring(s.indexOf(",") + 1);
s1 = s1.replace(" ", "");
s2 = s2.replace(" ", "");
//store both the strings in s1 and s2
System.out.println("First word: " + s1);
System.out.println("Second word: " + s2);
s1 = s1.trim();
s2 = s2.trim(); //remove extra spaces
System.out.println(s1 + " " + s2);
break;
}
}
}
}

java character position in a string

I was hoping that SO could help me with my issue. I have this code:
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter a character:\t");
String character = scanner.nextLine();
char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}
int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}
System.out.println("Character " + charVar + " appears " + count +
(count == 1 ? " time" : " times"));
}
So this code asks the user to enter a string, then it asks the user to enter a character, the program will then tell the user how many times that specific character appears. My problem is that I need to convert this code so it will still ask the user for the string, but wont ask for a character. It will instead ask for the user to enter a number. The program will then show what character is at that position in the string. Example: lets say they enter "string" and then 2 for the number, the program will display the character "r". So my question is basically if any one can give me an idea as how to accomplish this. Any help would be great.
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter an integer:\t");
int index = scanner.nextInt();
System.out.println("Character at position " + index + ": " + word.charAt(index));
}

Java string inside string

Write a program that asks the user to enter two Strings, and prints the number of times that the second String appears within the first String. For example, if the first String is "banana" and the second is "an", the program prints 2.
Below is my code so far
public class Assignment4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner answer = new Scanner(System.in);
//Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
//Ask the user to enter a second String
//look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
int counter = 0;
for(int i=0; i<input.length(); i++) {
if(input.charAt(i) == input2nd.charAt(0)) {
counter++;
}
}
System.out.println(input2nd + " appears " + counter + " times.");
When I type banana into first string, and second string is "an", the only thing come up is number 3, and it is for character a which appear 3 time, but not two as it suppose to only be 2 "an"
Consider this trick I learned years ago:
replace the searched word in the original word by emptychars...
get the diff between the length of both... searched chars and the original with replaced
divide that by the len of the searched word...
private static void searchString() {
Scanner answer = new Scanner(System.in);
// Prompt the user to enter a string
System.out.println("Enter a word:");
String input = answer.nextLine();
// Ask the user to enter a second String
// look at index method of string
System.out.println("Enter another word:");
String input2nd = answer.nextLine();
String a = input.replace(input2nd, "");
int counter = (input.length() - a.length()) / input2nd.length();
System.out.println(input2nd + " appears " + counter + " times.");
}
with the input banana and an will print 2

Struggling with my sentinel program

This is my first submission, I have completed one quarter of Java programming.
I have an assignment to create a Palindrome Checker. Fairly straight forward, I had that portion of the code figured out in the first hour. However, in typical fashion (for me) I want my code to do a bit more. This is where I run into issues.
I want this code to do the following:
Take user input
Correctly identify if the input is a palindrome regardless of case or punctuation
Run in a loop so that multiple tests can be performed
So far it works, I just don't know if I went about it the right way. Would anyone be willing to take a look and let me know how inefficient this is, or if it has any obvious rookie mistakes? Thanks so much.
Code:
/**
* Created by Travis on 1/10/2015.
*/
import java.io.IOException;
import java.util.*;
import javax.swing.*;
import java.text.*;
import java.lang.StringBuilder;
public class Palindrome
{
public static void main(String[] args) throws IOException //main class
{
String str = "", answer = "", test1 = "yes", test2 = "no"; //strings
int len = 10; //initial value for len so it doesn't trip the success if
Scanner KB = new Scanner(System.in); //user input
System.out.println("Greetings, Welcome to the Palindrome Checker.\n" + //initial greeting
"Would you like to check a Palindrome? (Yes or no)");
answer = KB.nextLine(); //input is for the sentinel program.
if (!(answer.equalsIgnoreCase(test1) || answer.equalsIgnoreCase(test2))) //error message in case user inputs incorrect string.
{
System.out.println("Error! You can only choose 'yes' or 'no'. Please try again:");
answer = KB.nextLine(); //allows for new answer
}
System.out.println(answer + " y"); //debugging so i can see answer
while (answer.equalsIgnoreCase(test1)) //compares to test1 which is: yes. as long as answer equals yes, the program should loop
{
System.out.println("Please provide a word or phrase:");
str = KB.nextLine(); //prompt for palindrome
String str2 = str.toLowerCase().replaceAll("\\s+", "").replaceAll("\\W+", ""); //converts input to a string that is a single group of chars with no space or punctuation
System.out.println(str2); //debug
StringBuilder str1 = new StringBuilder(str2); //takes the string and makes a stringbuilder so i can delete chars to test
len = str1.length(); //sets for length. This lets me account for any length of phrase
System.out.println(len); //debug
System.out.println(str1); //debug
for (int i = 0; len >= 2; i++) //for loop to progressively test front and back letters and proceed if they are the same
{
char ch1 = str1.charAt(0); //takes the letter at [0] and converts to char
char ch2 = str1.charAt(len - 1); //takes the last letter and converts to char
System.out.println("The first letter in your phrase is: " + ch1); // lists the letter at [0]
System.out.println("The last letter in your phrase is: " + ch2); //lists the letter at the end
if (!(ch1 == ch2)) //if the front and back letter do not match, fails and prompts for new phrase
{
System.out.println("Sorry, this phrase is not a palindrome. \n" +
"Would you like to try again?");
answer = KB.nextLine();
break;
}
else if (ch1 == ch2) //if front and back do match, removes front and back letters and updates stringbuilder
{
System.out.println("Removing letters on each end of the phrase and performing " +
"new check:\n");
str1.deleteCharAt(len - 1); //deletes the last letter from str1
str1.deleteCharAt(0); //deletes first letter from str1
len = str1.length(); //updates len with the new length of str1
i++;
}
}
if (len <= 1) //if the for loop successfully reduces stringbuilder to 1 or less characters, prompts for success
{
System.out.println("Congratulations, your phrase: '" + str + "' is a palindrome! \n\n" +
"Would you like to try again?");
answer = KB.nextLine();
len = 10; //resets len
}
}
if (answer.equalsIgnoreCase(test2)) //ends sentinel loop.
{
System.out.println(answer + " N");
System.exit(0);
}
}
}

Categories