Trying to create an Acronym out of user input - java

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.

Related

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.

Java - Read text file and store it using scanner, gives me empty ArrayList. Split words by using Delimeter

Task is to read an article of text from outside file and put each word (no signs) into and Array List as a separate String.
Although I´m sure my path is correct and readable(I can for example perform character count), no matter what I do my Array List of words from that article comes out as empty. I may be struggling with a way how to separate words from each other and other signs. Also with storing the result of reading.
I´ve been googling for the last 2 hours and reading similar answers here but no success. So decided for the first time to ask a question.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import org.w3c.dom.Text;
public class PlaceForErrors {
public static void main(String[] args) {
Scanner scan = null;
try {
scan = new Scanner(new File("\\Users\\marga\\Desktop\\objekt program\\oo2021\\w05_kontrolltoo1\\textHere.txt")).useDelimiter(" \\$ |[\\r\\n]+");
String token1 = "";
ArrayList<String> text = new ArrayList<String>();
while (scan.hasNext()) {
token1 = scan.next();
text.add(token1);
}
String[] textArray = text.toArray(new String[0]);
for(String element : textArray){
System.out.println(element);
}
//Controlling if the ArrayList is empty and it is
boolean tellme = text.isEmpty();
System.out.println(tellme);
} catch (FileNotFoundException exception) {
System.out.println(exception);
}
finally{
scan.close();
}
}
}
String[] textArray = text.toArray(new String[0]);
This line is your problem. You're trying to allocate the ArrayList into a String array of size 0, resulting in it appearing empty.
I would modify the array declaration to initialize using the ArrayList size, like so:
String[] textArray = text.toArray(new String[text.size()]);
Then you can see if your token delimiter works.
Quick recap of your steps
Your program does a lot. I counted 9 steps:
opens a (text) file as (text) input-stream to read from
create a scanner for tokens from this input-stream using a regular-expression as delimiter (= tokenizer)
scan for and iterate over each subsequent token (if any found) using a while-loop
each of this iteration adds the token to a list
if no more tokens, then iteration ends (or never started!): converts the list to array
loop over each array element using a for-each-loop and print it
check if originally collected list is empty and print true or false
catch the exception if file was not found and print the it
finally close any opened resources: the file that was read from
Now let's start to look for the step where something potentially could go wrong: the places for errors 😏️
Analysis: What can go wrong?
Look at the listed steps above and think of each from a what-could-go-wrong perspective, a quick check list (not correlated to the step-numbers above!):
Can your text-file be found, does it exist and is readable? Yes, otherwise any IOException like FileNotFoundException would have been thrown and printed.
Is the opened file empty with a size of 0 bytes? You can check using:
File textFile = new File("\\Users\\marga\\Desktop\\objekt program\\oo2021\\w05_kontrolltoo1\\textHere.txt");
System.out.println( "File size: " + textFile.length() );
// before passing the extracted file-variable to scanner
scan = new Scanner( textFile ).useDelimiter(" \\$ |[\\r\\n]+");
Does the delimiter/regex properly split/tokenize an example input string? Try:
// Just a separate test: same delimiter, with test-input
String delimiterRegex = " \\$ |[\\r\\n]+";
String testInput = " $ Hello\r\nWorld !\n\nBye.";
// so we create a new scanner
Scanner testScanner = new Scanner( testInput ).useDelimiter(delimiterRegex);
int tokenCount = 0;
while( testScanner.hasNext() ) {
tokenCount++;
System.out.println("Token " + tokenCount + ": " + testScanner.next() );
}
testScanner.close();
Should print 3 tokens (Hello, World !, Bye.) on 3 lines in console. The special sequence $ (space-dollar-space), any \n or \r (newline or carriage-return) are omitted and have split the tokens.
We should check the list directly after the while-loop:
// Not only checking if the ArrayList is empty, but its size (is 0 if empty)
System.out.println("Scanned tokens in list: " + text.size());
If it is empty, then we neither need to fill the array, nor loop to print will start (because nothing to loop).
Hope these explanations help you to perform the analysis (debugging/testing) yourself.
Let me know if it helped you to catch the issue.
Takeaway: Divide and conquer!
Why did I count the steps, above? Because all are potential places for errors.
In developer jargon we also say this main method of class PlaceForErrors has many responsibilities: counted 9.
And there is a golden principle called Single Responsibility Principle (SRP).
Put simply: It is always good to split a large problem or program (here: your large main method) into smaller pieces. These smaller pieces are easier to work with (mentally), easier to test, easier to debug if errors or unexpected happens. Divide & conquer!
If it works, start improving
You can split up this long method doing 9 steps into smaller methods.
Benefit: each method can be tested in isolation, like the testScanner.
If your program finally works as expected and your manual test went green.
Then you should post the working code to the sister-site: CodeReview.
Be curious and ask again, e.g. how to split up the methods, how to make testable, etc.
You'll get lot's of experienced advise on how to improve it even more.
Thank you for your input everyone!
Regarding the code, I went and checked everything step by step and on the way learned more about delimiters and scanner. I fixed my delimiter and everything worked just fine now.
Beside the fact that I made a newbie mistake and didn´t show the full code, as I though it would take away the attention from the main problem. I had two conflicting scanners in my main function(one I showed you and the other one was scanning again and counting letters A). And they both worked great separately(when one or the other is commented out), but refused to work together. So I found a way to combine them and use scanner only once. I will share my full code for reference now.
I learned my mistake, and will provide the my full code always in the future.
If someone is curious the full task was the following:
Read the text from a separate file using scanner and store it in an Array List.
Count how many letters "A" (small or big) there were and how big of % they made out of all the letters in the text.
Count how many words had one letter A, two letters A in them, etc.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Trying {
public static void main(String[] args) {
Scanner scan = null;
try {
//SCANNING FILE AND CREATING AN ARRAYLIST
scan = new Scanner(new File("\\Users\\marga\\Desktop\\objekt program\\oo2021\\w05_kontrolltoo1\\textHere.txt")).useDelimiter("[.,:;()?!\"\\s]+");
int aCount = 0;
int letterCount =0;
String token1 = "";
int wordWithAtLeastOneA = 0;
int wordWithA = 0;
int word1A = 0;
int word2A = 0;
int word3A = 0;
int word4OrMoreA = 0;
ArrayList<String> text = new ArrayList<String>();
// SCANNING EVERY WORD INTO AN ARRAY LIST
while(scan.hasNext()){
token1 = scan.next();
text.add(token1);
}
System.out.println("Amount of words in the scanned list is : " + text.size());
//COUNTING HOW MANY LETTERS 'A' TEXT HAS
for(String element : text){
for (int i=0;i<=element.length()-1;i++){
if (element.charAt(i) == 'A' || element.charAt(i) == 'a') {
aCount++;
}
}
}
System.out.println("There are "+aCount+" letters 'A'. ");
//HOW MANY LETTERS IN TOTAL TEXT HAS
for(String element : text){
for (int i=0;i<=element.length()-1;i++){
letterCount++;
}
}
//COUNTING HOW MANY WORDS HAVE 'A' LETTER IN THEM
for(String element : text){
for (int i=0;i<=element.length()-1;i++){
if (element.charAt(i) == 'A' || element.charAt(i) == 'a') {
wordWithAtLeastOneA++;;
break;
}
}
}
System.out.println("There are "+wordWithAtLeastOneA+" words that have at least one letter 'A' in them.");
System.out.println();
//COUNTING NUMBER OF WORDS THAT HAVE 1/2/3 or more 'A' LETTER IN THEM
for(String element : text){
wordWithA = 0;
for (int i=0;i<=element.length()-1;i++){
if (element.charAt(i) == 'A' || element.charAt(i) == 'a') {
wordWithA++;
if(wordWithA == 1){
word1A++;
}else if (wordWithA == 2){
word2A++;
}else if (wordWithA == 3){
word3A++;
}else if (wordWithA >= 4){
word4OrMoreA++;
}
}
}
}
System.out.println("There were "+ word1A+ " words, that had one letter 'A' in them." );
System.out.println("There were "+ word2A+ " words, that had two letters 'A' in them." );
System.out.println("There were "+ word3A+ " words, that had three letters 'A' in them." );
System.out.println("There were "+ word4OrMoreA+ " words, that had 4 or more letters 'A' in them." );
//COUNTING HOW MANY LETTERS THERE ARE IN TOTAL, COMPARE TO NUMBER OF "A" LETTERS
int percentOfA = aCount*100/letterCount;
System.out.println();
System.out.println("The entire number of letters is "+ letterCount+" and letter 'A' makes " + percentOfA+ "% out of them or " +aCount+ " letters.");
// for(String element : textArray){
// System.out.println(element);
// }
} catch (FileNotFoundException exception) {
System.out.println(exception);
}
finally{
scan.close();
}
}
}
And the text is:
Computer programming is an enormously flexible tool that you can use to do amazing things that are otherwise either manual and laborsome or are just impossible.
If you are using a smartphone, a chat app or if you are unlocking your car with the push of a button,
then you must know that all these things are using some kind of programming.
You are already immersed in the programs of different types.
In fact, software is running your life. What if you learn and start running these programs according to your will?
And the output is:
There are 35 words that have at least one letter 'A' in them.
There were 35 words, that had one letter 'A' in them.
There were 3 words, that had two letters 'A' in them.
There were 0 words, that had three letters 'A' in them.
There were 0 words, that had 4 or more letters 'A' in them.
The entire number of letters is 416 and letter 'A' makes 9% out of them or 38 letters.

A Program that Checks Consecutive Letters - Java

I'm looking for help with a question I have. We just started learning simple java in our course after learning a tonne of C++.
One of our bonus missions for people who know code more than what was taught in class.
The mission is as follows: Write a function by the name lettersSeries which gets letters (one letter at a time, assume all letters are lower case) inputted from the user. The function stops accepting letters from the user once the user has inputted 3 consecutive letters. (Only for loops can be used without while loops)
Example: a -> b -> a -> c -> d -> e (Here is stops)
As far I don't know much and I would be happy if someone would help me with this... I tried some options but I have no idea how to trace the alphabet, and especially how to check if letters are consecutive...
Thanks!
public static void letterSeries() {
//We create a scanner for the input
Scanner letters = new Scanner(System.in);
for(Here I need the for loop to continue the letters input) {
//Here I need to know if to use a String or a Char...
String/Char letter = next.<//Char or String>();
if(Here should be the if statement to check if letters are consecutive) {
/*
Here should be
the rest of the code
I need help with
*/
Obviously, you could change the code, and not make my pattern, I would just be happier with an easier way!
Here's how I would tackle the problem, I'm going to let you fill in the blanks with this though so I don't do all of your homework for you.
private void letterSeries() {
Scanner scanner = new Scanner(System.in);
char prevChar;
char currChar;
int amountOfConsecutives = 0;
final int AMOUNT_OF_CONSECUTIVES = 2;
for(;;) {
// Take in the users input and store it in currChar
// Check if (prev + 1) == currChar
// If true, amountOfConsecutives++
// If false, amountOfConsecutives = 0;
// If amountOfConsecutives == AMOUNT_OF_CONSECUTIVES
// Break out of the loop
}
}
You can use chars' Unicode number to check if letters are consecutive: if a and b are your letters, try to check if b - a == 1. If consequentiality is intended in a case-insensitive way ('B' consecutive to 'a') then check: (b - a == 1 || b - a == 33).
Scanner letters = new Scanner(System.in);
char previousChar = '\0';
int consecutive = 1;
for(; consecutive != 3 ;){
char userInput= letters.findWithinHorizon(".", 0).charAt(0);
if (userInput - previousChar == 1){
consecutive++;
} else {
consecutive = 1;
}
previousChar = userInput;
}
I cheated a little bit with this solution. I used a for loop with only the middle part so it acts like a while loop.
Anyway, here's how it works.
The first three lines create a scanner for user input, a consecutive variable that counts how many consecutive letters the user enters, and a previousChar to store the previous character.
"Why does consecutive start at 1?" you might ask. Well if the user enters one letter, it is going to be consecutive with itself.
In the for loop, as long as consecutive != 3, the code is going to run. The first line in the loop we read a character using findWithinHorizon(".", 0).charAt(0). And then the if statement checks whether it is a consecutive letter with the previous character. If it is, add one to consecutive and if not, reset consecutive to one. Lastly, we set previousChar to userInput to prepare for the next iteration.
private void letterSeries() {
Scanner letters = new Scanner(System.in);
String last = "";
int counter = 0;
for (;counter < 2;){
if ( last.equals (last=letters.next())) counter ++;
else counter = 0
}
}

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()

Java String output limiting range of String to Alphabet

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.

Categories