Force a stringBuilder to an upper case - java

I was wondering if there is anyway to use something like the toUpperCase for StringBuilder? Below is my code, I am trying to take user input of a phrase and turn it into an acronym. Someone helped me out by suggesting StringBuilder but I can't figure out if there is a way to make the acronym upper case. Any help is greatly appreciated.
public class ThreeLetterAcronym {
public static void main(String[] args) {
String threeWords;
int count = 0;
int MAX = 3;
char c;
//create stringbuilder
StringBuilder acronym = new StringBuilder();
Scanner scan = new Scanner(System.in);
//get user input for phrase
System.out.println("Enter your three words: ");
threeWords = scan.nextLine();
//create an array to split phrase into seperate words.
String[] threeWordsArray = threeWords.split(" ");
//loop through user input and grab first char of each word.
for(String word : threeWordsArray) {
if(count < MAX) {
acronym.append(word.substring(0, 1));
++count;
}//end if
}//end for
System.out.println("The acronym of the three words you entered is: " + acronym);
}//end main
}//end class

Just append upper case Strings to it :
acronym.append(word.substring(0, 1).toUpperCase())
or turn the String to upper case when getting the String from the StringBuilder :
System.out.println("The acronym of the three words you entered is: " + acronym.toString().toUpperCase());

Just append upper case String to StringBuilder.
//loop through user input and grab first char of each word.
for(String word : threeWordsArray) {
if(count < MAX) {
acronym.append(word.substring(0, 1).toUpperCase());
++count;
}//end if
}//end for
Or upper case the String when getting it from StringBuilder.
System.out.println("The acronym of the three words you entered is: " + acronym.toString().toUpperCase());
If you need a library take a look at Apache Common Lang WordUtils, WordUtils.capitalize(str).

Related

Java Scanner Class ( System.in)

I have the below code that is not reading or infinitely looping when a user inputs text using System.in. If I hard code the text into the Scanner variable it works fine so I am not sure what is wrong with the System.in portion of this code. Any help is appreciated.
import java.util.Scanner; // needed to use the Scanner class
public class HW2 {
static Scanner in = new Scanner(System.in);
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
while (in.hasNext()){
String word = in.next();
if (word.equals("the")){
the++;
}
else if( word.equals("and")){
and ++;
}
else if (word.equals("is")){
is++;
}
else if (word.equals("was")){
was++;
}
else noword++;
}
System.out.println("The number of occurrences of the was"+ the);
System.out.println("The number of occurrences of and was"+ and);
System.out.println("The number of occurrences of is was"+ is);
System.out.println("The number of occurrences of was was"+ was);
}
}
As has been mentioned, a Scanner attached to System.in will block while looking for more input. One way to approach this would be to read a single line in from the scanner, tokenize it, and then loop through the words that way. That would look something like this:
//...
String line = in.nextLine(); // Scanner will block waiting for user to hit enter
for (String word : line.split(" ")){
if (word.equals("the")) {
the++;
}
//...
You can always substitute one loop structure (for, while, do-while) for another. They all do the same thing, just with different syntax to make one a bit simpler to use than others depending on the circumstances. So if you want to use a while loop, you can do something like this:
// ...
String line = in.nextLine();
String[] tokens = line.split(" ");
int i = 0;
while (i < tokens.length){
String word = tokens[i];
if (word.equals("the")) {
the++;
}
// ...
i++;
} // end of the while loop
However, I'm of the opinion that a for loop is cleaner in the case of looping over a known set of data. While loops are better when you have an unknown dataset, but a known exit condition.
As System.in is always available while the program is running unless you close it. It will never exit the while loop. So you could add else if (word.equals("exit")) { break; }. This way, whenever you type 'exit' it will close the while loop and execute the code AFTER the while loop.
Depends, do you want to just read 1 line of text and then count the words individually?
Because is you want only one line you could take the input string using the Scanner library and split the string into individual words and apply the if-statement then. Something like:
public static void main(String [] args) {
System.out.println("Enter your line here");
int the =0;
int and =0;
int is = 0;
int was =0;
int noword =0;
String input = in.nextLine();
String words[] = input.split(" ");
for (String s : words) {
if (s.equals("the")){
the++;
} else if( s.equals("and")){
and++;
} else if (s.equals("is")){
is++;
} else if (s.equals("was")){
was++;
} else {
noword++;
}
}
System.out.println("The number of occurrences of the was: "+ the);
System.out.println("The number of occurrences of and was: "+ and);
System.out.println("The number of occurrences of is was: "+ is);
System.out.println("The number of occurrences of was was: "+ was);
}
This way you won't need a while loop at all. So it's more processor and memory efficient.

java characters in a string

so my problem is that I need to get the user to enter a string. then they will enter a character that they want counted. So the program is supposed to count how many times the character they entered will appear in the string, this is my issue. If someone can give me some information as to how to do this, it'll be greatly appreciated.
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they wan counted in the string
String character= keyboard.nextLine();
}
}
Here is a solution taken from this previously asked question and edited to better fit your situation.
Either have the user enter a char, or take the first character from
the string they entered using character.chatAt(0).
Use word.length to figure out how long the string is
Create a for loop and use word.charAt() to count how many times your character appears.
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they want counted in the string
String character = keyboard.nextLine();
char myChar = character.charAt(0);
int charCount = 0;
for (int i = 1; i < word.length();i++)
{
if (word.charAt(i) == myChar)
{
charCount++;
}
}
System.out.printf("It appears %d times",charCount);
This should do it. What it does is that it gets a string to look at, gets a character to look at, iterates through the string looking for matches, counts the number of matches, and then returns the information. There are more elegant ways to do this (for example, using a regex matcher would also work).
#SuppressWarnings("resource") 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"));

JAVA - store letters and number of letters in string

I am supposed to ask the user to enter a string and I am supposed to parse the string and keep track of the number of the alphabet. So like if the user enter the string "abee"
it displays the output as :
a: 1
b: 1
c: 0
e: 2
So far I have been able to get the string and parse it and store the elements into an array. And I have been able to print out each letter at a time with a for loop. Now the problem I am facing is that when it prints out the letters along with how many of the letters exist in the phrase the numbers don't match up. For example if I enter the letters : "abccddee"
it prints out:
a: 1
b: 1
c: 1
c: 0
d: 0
d: 0
e: 0
e: 0
For testing purposes I am using my own string rather than using the scanner.
import java.util.Scanner;
public class CountLetters
{
public static void main(String[] args)
{
//create arrays
String[] upper = new String[25];
String[] lowerChar = new String[25];
int [] lowerCharNum = new int[25];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a phrase");
//grab phrase from user
String phrase = "abccddee";
//create array with the size of the phrase entered from user
String[] letters = new String[phrase.length()];
System.out.println("letters length: " + letters.length);
//separate every letter in phrase and store it into array "letters"
letters = phrase.split("");
for(int i=0; i<letters.length; i++)
{
lowerChar[i] = letters[i];
switch(letters[i])
{
case "a":
lowerCharNum[0] += 1;
break;
case "b":
lowerCharNum[1] += 1;
break;
case "c":
lowerCharNum[2] += 1;
break;
case "d":
lowerCharNum[3] += 1;
break;
case "e":
lowerCharNum[4] += 1;
break;
case "f":
lowerCharNum[5] += 1;
break;
}//end of switch
System.out.println(lowerChar[i] + ": " + lowerCharNum[i]);
}
}//end of main method
}//end of class
Rather than working with simple array you can work with java's Collection's HashMap.
With HashMap the main working goes around with the for loop, will check if the Character is already present in the HashMap if it is then we will get the value associated with Character and will add 1 with the existing value and if the Character is not present then we will put a Character in HashMap and will store the initial count 1 with the associated character.
HashMap<Character, Integer> lettersCount = new HashMap<>();
String phrase = "abccddee";
int length = phrase.length();
int count = 1;
for (int i = 0; i < length; i++) {
int integer = 0;
char charAt = input.charAt(i);
if (!lettersCount.containsKey(charAt)) {
lettersCount.put(charAt, 0);
}
integer = lettersCount.get(charAt);
integer = initialCount + integer;
lettersCount.put(charAt, integer);
}
System.out.println(lettersCount);
You are using array which you will be needed to intialize first at time of declaration this will create a extra memory space which will be waste if all 26 letters are not being encountered and as per the code you have provided in the question you are allocating 3 arrays so it will take much more memory, So rather this solution will require only a HashMap (HashMap will allocate memory according to the key and value inserted in HashMap)and a for loop which will just compute the occurence of Charater and to use it again further in your program will be much more easier with it.
You are printing within the for loop. You should print the frequency outside that loop.
The method which you are using is not scalable. You will have to write 52 case statements in your switch given that the phrase consists only of uppercase and lowercase English alphabets.
A better way to do the same would be to use the ASCII encoding for your purpose. You can have something on the following lines:
int frequency[] = new int[128];
for (int i = 0; i < phrase.length(); i++) {
frequency[(int) phrase.charAt(i)]++;
}
In this method frequency array is used to count the occurrences of first 128 ASCII characters in phrase string. Operation (int) phrase.charAt(i) simply converts the character into corresponding ASCII code and we increase the counter for that character by 1. At the end of the processing, frequency array will contain the number of occurrences of first 128 ASCII characters in the given phrase string. Simply print this frequency to achieve desired output.
print statement must be outside the while for loop.
System.out.println(lowerChar[i] + ": " + lowerCharNum[i]);
updated:
you need to parse entire string first, then start printing.
import java.io.*;
import java.util.*;
class CountLetters {
public static void main(String[] args)
{
int i;
//create arrays
String[] upper = new String[25];
String[] lowerChar = new String[25];
int [] lowerCharNum = new int[25];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a phrase");
//grab phrase from user
String phrase = "abccddee";
//create array with the size of the phrase entered from user
String[] letters = new String[phrase.length()];
System.out.println("letters length: " + letters.length);
//seperate every letter in phrase and store it into array "letters"
letters = phrase.split("");
for(i=0; i<letters.length; i++)
{
lowerChar[i] = letters[i];
switch(letters[i])
{
case "a":
lowerCharNum[0] += 1;
break;
case "b":
lowerCharNum[1] += 1;
break;
case "c":
lowerCharNum[2] += 1;
break;
case "d":
lowerCharNum[3] += 1;
break;
case "e":
lowerCharNum[4] += 1;
break;
case "f":
lowerCharNum[5] += 1;
break;
}//end of switch
}
for(i=0;i<5;i++)
System.out.println(lowerChar[i] + ": " + lowerCharNum[i]);
}//end of main method
}//end of class
Your solution with arrays is a bit complicated. By using a Map instead we can directly associate the encountered characters with the number of times they have been encountered, thus making it very straight-forward to increase the counter and to output the counter without having to look up indices in different arrays.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CountLetters
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a phrase");
//grab phrase from user
String phrase = "abccddee";
//create array with the phrase entered from user
char[] letters = phrase.toCharArray();
System.out.println("letters length: " + letters.length);
// Map to keep track of all encountered characters and the
// number of times we've encountered them
Map<Character, Integer> characterCounts = new HashMap<>();
for(int i=0; i<letters.length; i++)
{
Character character = letters[i];
if(characterCounts.containsKey(character))
{
// We've encountered this character before, increase the counter
characterCounts.put(character, characterCounts.get(character) + 1);
}
else
{
// This is the first time we encounter this character
characterCounts.put(lowerChar, 1);
}
}
// Iterate over all character-counter pairs and print them
for(Map.Entry<Character, Integer> entry : characterCounts.entrySet())
{
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}//end of main method
}//end of class
HashMap - Stores keys and values in an unordered way and contains only unique keys.
TreeMap - Stores keys and values in a naturally ordered way and contains only unique keys.
LinkedHashMap - Stores keys and values in the order of keys insertions and contains only unique keys.
The appropriate data structure for such requirement will be a Map. If you want to maintain the order of letters in which they appeared in the String, you can use LinkedHashMap, if the order of letters in not a concern then you can you a HashMap. I am using LinkedHashMap for my example.
public class Test {
public static void main(String[] args) {
//Taking the input from the user
System.out.println("Enter the String"); //I am entering "abccddee" for your example
Scanner sc = new Scanner(System.in);
String input = sc.next();
//LinkedhashMap preserves the order in which input was supplied
LinkedHashMap<Character, Integer> lhm = new LinkedHashMap<Character, Integer>();
for(int i=0; i<input.length(); i++){
//method get will return null if the letter is not available at the given index else it will return the count
Integer j = lhm.get(input.charAt(i));
//If the chracter was not present in the String
if(j==null)
lhm.put(input.charAt(i),1);
//If the character was present in the String
else
lhm.put(input.charAt(i),j+1);
}
for(Character c : lhm.keySet())
System.out.println(c+": "+lhm.get(c)+" ");
}
}
The output will be:
a: 1
b: 1
c: 2
d: 2
e: 2

Uppercase, lowercase and other counter

So I've been making a small piece of code in Java that takes input from the user counts the uppercase, lowercase and other parts (such as spaces, numbers, even brackets) and then returns how much there are of each to the user.
The problem I have is that say I put in "Hello There" it stops counting spots after the "o" in Hello. So after the first word.
Code
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int upper = 0;
int lower = 0;
int other = -1;
int total = 0;
String input;
System.out.println("Enter the phrase: ");
input = scan.next();
for (int i = 0; i < input.length(); i++) {
if (Character.isUpperCase(input.charAt(i))) upper++;
if (Character.isLowerCase(input.charAt(i))) lower++;
else other++;
total = upper + lower + other;
}
System.out.println("The total number of letters is " + total);
System.out.println("The number of upper case letters is " + upper);
System.out.println("The number of lower case letters is " + lower);
System.out.println("The number of other letters is " + other);
}
}
Scanner#next:
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern.
The problem is that next doesn't see the word "There" since "Hello World" is not a complete token.
Change next to nextLine.
Advice: Use the debugger and you'll find the problem quickly, and when you have doubts refer to the docs, they're there for you.
Problem is that next() only returns the line before a space but nextLine() will read the whole line.
So Change
scan.next();
to
scan.nextLine();
You need to change next() to nextLine()- it will read all the line
As others have said. You should change from scn.next to scn.nextLine(). But why? This is because scn.next() only read until it encounters a space, and it stops reading. So whatever input after a space will not be read.
scn.nextLine() reads until a newline (i.e. enter) is encountered.
You can try with regular expressions:
public static void main(String[] args) {
String input = "Hello There";
int lowerCase = countMatches(Pattern.compile("[a-z]+"), input);
int upperCase = countMatches(Pattern.compile("[A-Z]+"), input);
int other = input.length() - lowerCase - upperCase;
System.out.printf("lowerCase:%s, upperCase:%s, other:%s%n", lowerCase, upperCase, other);
}
private static int countMatches(Pattern pattern, String input) {
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}

Palindromes in a Statement: Java

I need some help with a palindrome detector that I am doing for homework. I need the user to enter a statement, so more then one word, and the program needs to detect which words are a palindrome and which ones are not. However, something in my loop is going wrong in that, it will only detect the first word then blend the others after together. I'm not sure what I'm doing wrong.
import javax.swing.JOptionPane;
public class Main {
static int numpali = 0;
public static void main(String[] args) {
// ask the user to enter a statement
String statement = JOptionPane.showInputDialog("Enter a Statement");
String reverse = "";
// Array to split the sentence
String[] words = statement.split(" ");
// Run a loop to seperate the words in the statement into single Strings
for (String word : words) {
// Print out original word
System.out.println(word + "\n");
int wordlength = word.length();
// send the word to lowercase so capitals are negligible
String wordlower = word.toLowerCase();
// Run a loop that reverses each individual word to see if its a
// palindrome
for (int t = wordlength; t > 0; t--) {
reverse += wordlower.substring(t - 1, wordlength);
wordlength--;
}
System.out.println(reverse);
// show a message if the word is a palindrome or not, and add 1 to the
// total number of palindromes
if (reverse.equals(wordlower)) {
JOptionPane.showMessageDialog(null, word + " is a Palindrome!");
numpali = numpali + 1;
}
word = "";
}
System.out.println("Number of Palindromes:" + "\n" + numpali);
}
}
I've tried to explain what its doing the best I can inside the program.
You never reset the "reverse" value inside your loop. So after the first word your just adding more characters to "reverse" every iteration.
Put
reverse = "";
inside your main for loop
Reset the value of reverse to reverse=""; just like what you have done word="";

Categories

Resources