Java String output limiting range of String to Alphabet - java

I'm currently doing an exercise(not homework before anyone gives out) and I am stuck in the final part of the question.
The question is:
Write a program which will input a String from the keyboard, output the number of
seperate words, where a word is one or more characters seperated by spaces. Your
program should only count words as groups of characters in the rang A..Z and a..z
I can do the first part no problem as you can see by my code:
import java.util.Scanner;
public class Exercise10 {
public static void main(String[] args) {
String input;
int counter = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your text: ");
input = keyboard.nextLine();
for(int i = 0; i < input.length(); i++){
if(input.charAt(i) == ' '){
counter++;
}
}
System.out.println(counter + 1);
keyboard.close();
}
}
However the part that is confusing me is this:
Your program should only count words as groups of characters in the rang A..Z and
a..z
What should I do in this instance?

I won't give you a full answer but here are two hints.
Instead of counting spaces look at splitting the string and looping through each element from the split:
Documentation
Once you have the String split and can iterate through the elements, iterate through each character in each element to check if it is alphabetic:
Hint

I believe it should not consider separate punctuation characters as words. So the phrase one, two, three ! would have 3 words, even if ! is separated by space.
Split the string on spaces. For every token, check the characters; if at least one of them is in range a..z or A..Z, increment counter and get to the next token.

Related

Stop reading user's input when specific character is inserted

So I have this exercise:
"Create a program that reads characters from the keyboard until it receives a dot.
The program must count the number of spaces.
Indicate the total number of spaces at the end of the program."
My problem is, everytime I type a character, I have to press "Enter", for it to register. This way it acknoledges the dot, but not the spaces, and it's also not practical, the point is to type the whole sentence, and ackowlegde the dot, and proceed with the rest of the code.
If I type the whole sentence (ex.: "I ate food."), it does not acknowledge the dot, and lets me keep writing.
This link: Java Scanner: stop reading after the first entry, suggests reading character by character, which is a thing I don't want.
This link: Java Scanner stop reading input if receives bad character, this one did not help me either.
package m1_praticas;
import java.util.Scanner;
public class M1_Pratica3_ContarEspacos {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char input;
String sentence = "";
//int white_spaces = 0;
System.out.println("Escreva uma frase:");
do{
input = scanner.next().charAt(0);
sentence += input;
} while(input != '.');
//for(char c : sentence.toCharArray()){
//if(c == ' '){
//white_spaces++;
//}
//}
System.out.println(sentence);
System.out.println(white_spaces);
}
}
In short, what I want, is when the user is typing a sentence, there is someking of method that is reading the sentence charater, by character.
Once that method meets the dot, it performs the rest of the code. Is that possible, or do I always have to hit "enter", to register a key?
Thanks in advance.

How to Find the word that comes after a specified word in java String

My program has a String inputted Eg. hello i am john who are you oh so i see you are also john i am happy
my program then has a keyword inputted Eg. i (the program doesn't like capitals or punctuation yet)
then it reads the initial String and finds all the times it mentions the keyword + the word after the keyword, Eg. i am, i see, i am.
with this is finds the most common occurrence and outputs that second word as the new keyword and repeats. this will produce
i am john/happy (when it comes to an equal occurrence of a second word it stops (it is meant to))
What i want to know is how i find the word after the keyword.
package main;
import java.util.Scanner;
public class DeepWriterMain {
public static void main(String[] args) {
String next;
Scanner scanner = new Scanner(System.in);
System.out.println("text:");
String input = scanner.nextLine();
System.out.println("starting word:");
String start = scanner.nextLine();
input.toLowerCase();
start.toLowerCase();
if (input.contains(start)) {
System.out.println("Loading... (this is where i find the most used word after the 'start' variable)");
next = input.substring(5, 8);
System.out.println(next);
}else {
System.out.println("System has run into a problem");
}
}
}
If you use split to split all your words into an array, you can iterate through the array looking for the keyword, and if it is not the last in the array, you can print the next word
String arr [] = line.split(" ");
for (int i = 0; i < arr.length -1; i++) {
if (arr[i].equalsIgnoreCase(keyword)) {
sop(arr[i] + " " arr[i + 1]);
}
if it is not the last in the array, iterate only to length - 1
The String class includes a method called public int indexOf(String str). You could use this as follows:
int nIndex = input.indexOf(start) + start.length()
You then only need to check if nIndex == -1 in the case that start is not in the input string. Otherwise, it gets you the position of the first character of the word that follows. Using the same indexOf method to find the next space provides the end index.
This would allow you to avoid a linear search through the input, although the indexOf method probably does one anyway.

Hanging Letter Program

I was practicing problems in JAVA for the last few days and I got a problem like this:
I/p: I Am A Good Boy
O/p:
I A A G B
m o o
o y
d
This is my code.
System.out.print("Enter sentence: ");
String s = sc.nextLine();
s+=" ";
String s1="";
for(int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if(c!=32)
{s1+=c;}
else
{
for(int j=0;j<s1.length();j++)
{System.out.println(s1.charAt(j));}
s1="";
}
}
The problem is I am not able to make this design.My output is coming as each character in each line.
First, you need to divide your string with space as a delimiter and store them in an array of strings, you can do this by writing your own code to divide a string into multiple strings, Or you can use an inbuilt function called split()
After you've 'split' your string into array of strings, just iterate through the array of strings as many times as your longest string appears, because that is the last line you want to print ( as understood from the output shared) i.e., d from the string Good, so iterate through the array of strings till you print the last most character in the largest/ longest string, and exit from there.
You need to handle any edge cases while iterating through the array of strings, like the strings that does not have any extra characters left to print, but needs to print spaces for the next string having characters to be in the order of the output.
Following is the piece of code that you may refer, but remember to try the above explained logic before reading further,
import java.io.*;
import java.util.*;
public class MyClass {
public static void main(String args[]) throws IOException{
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
// Split is a String function that uses regular function to split a string,
// apparently you can strings like a space given above, the regular expression
// for space is \\s or \\s+ for multiple spaces
int max = 0;
for(int i=0;i<s.length;i++) max = Math.max(max,s[i].length()); // Finds the string having maximum length
int count = 0;
while(count<max){ // iterate till the longest string exhausts
for(int i=0;i<s.length;i++){
if(count<s[i].length()) System.out.print(s[i].charAt(count)+" "); // exists print the character
else System.out.print(" "); // Two spaces otherwise
}
System.out.println();count++;
}
}
}
Edit: I am sharing the output below for the string This is a test Input
T i a t I
h s e n
i s p
s t u
t

Counting a String's Lowercase Letters

I was looking around forums and found a helpful code on how to count lowercase letters in an inputted string. Thing is, after testing it, I saw it only counts lowercase letters within the first word typed. So, for example, if I type: HeRE the counter will say I've typed in 1 lowercase letter (which is correct), but if I type in: HeRE i am the counter will still only say 1 instead of 4. It's only counting the lowercase letters in the first word. How do I get it to count lowercase letters in my entire string?
Code thus far:
import java.util.Scanner;
public class countingLowerCaseStrings {
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your string: ");
String input = scanner.next();
int LowerCaseLetterCounter = 0;
for (char ch : input.toCharArray()) {
if (Character.isLowerCase(ch)) {
LowerCaseLetterCounter++;
}
}
System.out.println ("Number of lower case letters in this string is: " +
LowerCaseLetterCounter);
}
}
Thanks a bunch for the help!
scanner.next(); reads the first available word, not the entire line.
So if you input "HeRE i am" it will just read "HeRE".
Change it to scanner.nextLine():
System.out.println("Enter your string: ");
String input = scanner.nextLine();
DEMO - look at stdin and stdout panels.
As a matter of interest, Java 8 provides a fairly streamlined way of achieving the same thing:
scanner.nextLine().chars().filter(Character::isLowerCase).count()

Trying to create an Acronym out of user input

Hello I am working on an assignment and I'm running into issues I was hoping for a little direction...
The purpose is to have user input a phrase and create an acronym out of that phrase. Anything over three words will be ignored.
I'm having issues with the acronym part, I am able to get the first character and figured that I would loop through the user input and grab the character after a space, but that is not working. All I am getting is the first character, which is obvious because I grab that first, but I can't figure out how to "save" the other two characters. Any help is greatly appreciated.
*********UPDATE************************
So thanks to an answer below I have made progress with using the StringBuilder. But, now if I enter "Your Three Words" the Output is: YYYYYTYYYYYWYYYY
Which is progress but I can't understand why it's repeating those first characters so many times??
I edited the code too.
*********UPDATE*****************************
public class ThreeLetterAcronym {
public static void main(String[] args) {
String threeWords;
StringBuilder acronym = new StringBuilder();
Scanner scan = new Scanner(System.in);
System.out.println("Enter your three words: ");
threeWords = scan.nextLine();
for(int count = 0; count < threeWords.length(); count++) {
acronym.append(threeWords.charAt(0));
if(threeWords.charAt(count) == ' ') {
++count;
acronym.append(threeWords.charAt(count));
}
}
System.out.println("The acronym of the three words you entered is: " + acronym);
}
}
You can't save the other characters because char is supposed to store only one character.
You can use a StringBuilder in this case
StringBuilder acronym = new StringBuilder();
Then in your loop simply replace it with
String[] threeWordsArray = threeWords.split(" ");
for(String word : threeWordsArray) {
acronym.append( word.substring(0, 1) );
}
**updated
You store the character at the current index in space:
char space = threeWords.charAt(count);
Then you compare the value of space with the integer value 3:
if(space < 3)
This will almost certainly never be true. You are asking for the numeric value of a character. Assuming it is a letter it will be at least 65. I suspect that your intention is to store something different in the variable space.

Categories