Strings getting messed up within the loop - java

So guys, I've made a program that counts how many words and letters a given sentence has. For instance, if my input is "stack overflow", it would return 2 WORDS and 13 LETTERS. But I've been having a problem to read single letters that are also contained in another word within the sentence. For example, the input "a alex" has been returning me 2 words and 4 LETTERS, when it should be returning 5 letters... I noticed that, as soon as it reads the first "a", the second string "alex" becomes "lex" for some reason, but I don't know how to solve it... here's the snippet, thx in advance!
package Uri;
import java.util.Scanner;
import java.lang.Math;
import java.lang.StringBuilder;
public class Facil{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String lida=sc.nextLine();
int letras=0, palavras=0;
while(lida != ""){
System.out.println("current sentence = " + lida);
if (lida.charAt(0) == ' ') {
lida = lida.replaceFirst(" ", "");
continue;
}
if (!lida.contains(" ")) {
palavras++;
letras+=lida.length();
System.out.println("quantity of added letters = " + lida.length());
break;
}
String separada = lida.substring(0,lida.indexOf(" "));
System.out.println("separated word = " + separada);
if (!separada.contains("..") && separada.endsWith(".") || !separada.contains(".")){
palavras++;
letras+=separada.length();
lida = lida.replace(separada, "");
System.out.println("added letters = " + separada.length());
}
}
System.out.println("\n RESULT: ");
System.out.println("quantity of words = " + palavras);
System.out.println("quantity of letters = " + letras);
}
}
}

Your problem comes from lida = lida.replace(separada, ""); where you replace 'a' with space
How about using lida.split(" ") then get the length of the array for the number of words? And for each word, use String.length() to count for the letters?

Related

How do I find word in an array and find how many characters later does it appear in the array in java?

So I have the following program where I am able to get user's input, reverse the input and find out how long it is (character wise) but I do not know how to find a keyword in the user's input (which I have tuned it into an array) and don't know how to tell after how many characters later does the keyword begin after.
import java.util.*;
import java.lang.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("------------------------------------------------------");
System.out.println("Enter The String (With Space Separating The Words):");
System.out.println("------------------------------------------------------");
String usrInput = sc.nextLine().toLowerCase();
String output[] = usrInput.split(" ");
String arrayOutput = "";
for (int i = output.length - 1; i >= 0; i--) {
arrayOutput += output[i];
if (i != 0) {
arrayOutput += " ";
}
}
System.out.println("------------------------------------------------------");
System.out.println("You entered:\n");
for(String j : output) { System.out.println(j); }
System.out.println("\nIt is " + usrInput.length() + " characters long");
System.out.println("You entered " + output.length + " words.");
System.out.println("The reversed string is: " + arrayOutput);
System.out.println("------------------------------------------------------");
}
}
You might try looking at String docs. From what you are trying to describe i assume you will need indexOf method.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)
Be sure to check right java version docs for your need.

Trying to get the length of a sentence from a user input but it stops after the first word and space

The Java task is to have the user type a sentence/phrase and then print out how many characters the sentence has. My .length() method is only counting the first word and space as characters. I've read previous questions and answers involving nextLine() but if I use that instead of next() it only lets the user type it's question and waits, doesn't print anything else immediately anymore. I'm brand new to Java and I think this can be fixed with a delimiter but I'm not sure how or what I'm missing. TIA!!
Update: Here's my code.
import java.util.Scanner;
class StringStuff{
public static void main( String [] args){
Scanner keyboard = new Scanner(System.in);
int number;
System.out.print("Welcome! Please enter a phrase or sentence: ");
System.out.println();
String sentence = keyboard.next();
System.out.println();
int sentenceLength = keyboard.next().length();
System.out.println("Your sentence has " + sentenceLength + " characters.");
System.out.println("The first character of your sentence is " + sentence.substring(0,1) + ".");
System.out.println("The index of the first space is " + sentence.indexOf(" ") + ".");
}
}
when I type "Hello world." as the sentence it prints:
Your sentence has 6 characters.
The first character of your sentence is H.
The index of the first space is -1.
keyboard.next call is waiting for user input. You're calling it twice, so your program expects the user to enter two words.
So, when you type in "Hello world." it reads "Hello" and "world." separately:
//Here, the sentence is "Hello"
String sentence = keyboard.next();
System.out.println();
//Here, keyboard.next() returns "World."
int sentenceLength = keyboard.next().length();
And when you use nextLine your code is waiting for the user to enter two lines.
To fix this you need to:
Read the whole line with nextLine.
Use sentence instead of requesting user input the second time.
Something like this should work:
String sentence = keyboard.nextLine();
System.out.println();
int sentenceLength = sentence.length();
import java.util.Scanner;
public Stringcount
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("enter the sentence:");
String str=s.nextLine();
int count = 0;
System.out.println("The entered string is: "+str);
for(int i = 0; i < str.length(); i++)
{
if(str.charAt(i) != ' ')
count++;
}
System.out.println("Total number of characters in the string: " + count);
System.out.println("The first character of your sentence is " + str.substring(0,1) + ".");
System.out.println("The index of the first space is " + str.indexOf(" ") + ".");
}
}

Counting matching characters on a string

I have been asked to created a program that asks the user for two inputs, both of which have to be stored as strings. The first input can be one or multiple words, and the second input has to be one sole character. After the user enters both inputs the program should count how many times, if any, the sole charter appears in the first string. Once the iteration through the first string is done the program should then output the number of instances of the second string. Example:
"There is 1 occurrence(s) of 'e' in test."
The program must use the a while loop and string values. This is the solution I have as of right now following the parameters established by the professor
public static void main(String[] args) {
String inputEntry; // User's word(s)
String inputCharacter; // User's sole character
String charCapture; // Used to create subtrings of char
int i = 0; // Counter for while loop
int charCount = 0; // Counter for veryfiying how many times char is in string
int charCountDisplay = 0; // Displays instances of char in string
Scanner scan = new Scanner(System.in);
System.out.print("Enter some words here: "); // Captures word(s)
inputEntry = scan.nextLine();
System.out.print("Enter a character here: "); // Captures char
inputCharacter = scan.nextLine();
if (inputCharacter.length() > 1 || inputCharacter.length() < 1) // if user is not in compliance
{
System.out.print("Please enter one character. Try again.");
return;
}
else if (inputCharacter.length() == 1) // if user is in compliance
{
while( i < inputEntry.length()) // iterates through word(s)
{
charCapture = inputEntry.substring(charCount); // Creates substring of each letter in order to compare to char entry
if (charCapture.equals(inputCharacter))
{
++charCountDisplay;
}
++charCount;
++i;
}
System.out.print("There is " + charCountDisplay +
" occurrence(s) of " + inputCharacter + " in the test.");
}
}
This iteration has a bug. Instead of counting all the instances of the inputCharacter variable it only counts up to one, regardless of how many instances appear on the string. I know the problem is in this part of the code:
while( i < inputEntry.length()) // iterates through word(s)
{
charCapture = inputEntry.substring(charCount); // Creates substring of each letter in order to compare to char entry
if (charCapture.equals(inputCharacter))
{
++charCountDisplay;
}
++charCount;
++i;
}
I just can't quiet pin down what I'm doing wrong. It seems to me that the charCountDisplay variable reverts to zero after each iteration. Isn't that supposed to be avoided by declaring the variable at the very beginning?... I'm one confused fellow.
This is wrong
charCapture = inputEntry.substring(charCount);
does not return one char
try using inputEntry.charAt(charCount)
Another hint is to define your variables close to where you use them rather than at the top of your method like:
String inputEntry;
inputEntry = scan.nextLine();
Even better would be to do inline
String inputEntry = scan.nextLine();
It will make your code a lot more concise and readable.
A more concise way to do your code is:
Scanner scan = new Scanner(System.in);
System.out.print("Enter some words here: "); // Captures word(s)
String inputEntry = scan.nextLine();
System.out.print("Enter a character here: "); // Captures char
String inputCharacter = scan.nextLine();
// validate
// then
int len = inputEntry.length();
inputEntry = inputEntry.replace(inputCharacter, "");
int newlen = inputEntry.length();
System.out.format("There is %d occurrence(s) of %s in the test.%n",
len - newlen, inputCharacter);
output
Enter some words here: scarywombat writes code
Enter a character here: o
There is 2 occurrence(s) of o in the test.
Here is a complete MVCE:
package com.example.countcharacters;
/**
* EXAMPLE OUTPUT:
* Enter some words here:
* How now brown cow
* Enter a character here:
* abc
* Please enter one character. Try again.
* Enter a character here:
* o
* There are 4 occurrence(s) of o in the text How now brown cow.
*/
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Captures word(s)
String inputEntry;
System.out.println("Enter some words here: ");
inputEntry = scan.nextLine();
// Captures char
char inputCharacter;
while (true) {
System.out.println("Enter a character here: ");
String line = scan.nextLine();
if (line.length() == 1) {
inputCharacter = line.charAt(0);
break;
} else {
// if user is not in compliance
System.out.println("Please enter one character. Try again.");
}
}
// iterates through word(s)
int charCountDisplay = 0;
int i = 0;
while(i < inputEntry.length()) {
char c = inputEntry.charAt(i++);
if (c == inputCharacter) {
++charCountDisplay;
}
}
// Print results
System.out.print("There are " + charCountDisplay +
" occurrence(s) of " + inputCharacter +
" in the text " + inputEntry + ".");
}
}
NOTES:
You can use "char" and "String.charAt()" to simplify your code.
In general, it's preferable to declare variables close to where you use them (rather than at the top).
You can put your test for "one character only" in its own loop.
'Hope that helps!
inputEntry.chars().filter(tempVar -> tempVar == inputCharacter).count() will give you the number of occurrences of a character in the string.
String inputEntry = "text";
char inputCharacter = 'x';
System.out.print("There is " + inputEntry.chars().filter(tempVar -> tempVar == inputCharacter).count() + " occurrence(s) of " + inputCharacter + " in the text " + inputEntry + ".");

How to fix: errorjava.util.regex.PatternSyntaxException for pig latin translator

In my pig latin translator I am getting:
errorjava.util.regex.PatternSyntaxException: Unclosed character class near index 10
[C#55f96302
Every time I compile it.
My code has two methods one to remove the special character at the end of the user input and split the words up, and another to actually translate the words.
Here is my code:
package midtermPigLatin;
import java.util.Scanner;
import java.util.Arrays;
import textio.TextIO;
public class midtermPigLatin {
public static void main(String[] args)
{
String yourSentence="", line = "", single,line1 = "", pigLatin = "";
Scanner input = new Scanner( System.in );
Scanner word = new Scanner(line);
String[] words;
char[] special = {'.', '?','!'};
String specialChar = special.toString();
boolean again = true;
try {
System.out.print("Enter your words here: ");
label1: while(input.hasNextLine())
{
line = input.nextLine();
line1 = line.replaceAll(specialChar, "");
word = new Scanner (line);
while(word.hasNext())
{
single = word.next();
pigLatin = pigLatin(single);
if (word.hasNext())
{
System.out.print(pigLatin + " " );
}
else if(!word.hasNext())
{
System.out.print( pigLatin);
break label1;
}
}
}
}catch(Exception errMsg)
{
System.out.print(" error" + errMsg);
}
}
public static String pigLatin(String single)
{
String newWord = "";
try
{
if (single.startsWith("a") || single.startsWith("e") || single.startsWith("i") || single.startsWith("o") || single.startsWith("u"))
newWord = (single + "way ");
else if (single.startsWith("sh") || single.startsWith("ch") || single.startsWith("th"))
newWord =(single.substring(2)+single.substring(0,2)+"ay ");
else
newWord = (single.substring(1)+single.substring(0,1)+"ay ");
}
catch (Exception errMsg)
{
System.out.println("Error in special" + errMsg);
}
return newWord;
}
}
Per my professors rules I need to have at least two methods and try-catches so
I can't take those out.
In the String class replaceAll uses a regex not a single character. . and ? are special characters in regex they mean any character or optional respectively.
There is two ways you could solve this.
1 Use String.replace() it takes a single character and replaces every occurrence of that character. You should also make it a String[] and then loop through each string and replace it.
String[] special = {".", "?", "!"};
for(String specialChar : special) {
line = line.replace(specialChar, "");
}
2 You could change your char[] to a String and use real regex
String[] specialChar = "[\\.\\?!]"
Either will take care of your compile error.
Update:
I forgot Java makes you escape \

Finding the middle ten characters of a sentence + printing more text on each line

So pretty much, I have this piece of code. It's intended to take a sentence, and print each word on its own line. It's also supposed to find the middle ten characters of a sentence.
My problem is that I'm unsure how to make it so that I actually get the middle ten characters of a sentence. Currently in the code, it's written so that it finds the last two digits. Also, I would like to make it so that instead of having only the words print out on each line, I'd like it to say
"first word: this" "second word: is" and so forth. Still, each on a separate line. Any help or guidance would be very appreciated, thank you!
import java.util.Scanner;
public class Sentence {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a sentence with 5+ words: ");
String sentence = in.nextLine();
System.out.println();
int space = sentence.indexOf(" ");
sentence = sentence.substring(0, space) + "\n" + sentence.substring(space + 1);
System.out.println(sentence.replaceAll("\\s+", "\n"));
String substring = sentence.length() > 10 ? sentence.substring(sentence.length() / 2) : sentence;
System.out.println();
System.out.println("MIDDLE 10 CHARACTERS: " + substring);
}
}
Try this:
String sentence = "He went to Accra today";
while((sentence.length() < 10) || (sentence.length() > 10)){
sentence = sentence.substring(1);
sentence = sentence.substring(0,sentence.length()-1);
}
System.out.println("Middle 10 is \""+sentence+"\"");
Output:
Middle 10 is "t to Accra"

Categories

Resources