Java strings arrays - java

I'm having trouble with my program. I need to enter only capital letters, R,B,W. Validate the correct input and then sort the string. Output should be sorted with R's first, B's second and W's third. I can only get the alphabetized output, not the needed output. I don't know what to do next.
System.out.print("Enter a string of capital letters made up of R, B, W: ");
Scanner s = new Scanner(System.in);
String letters;
for (letters = s.nextLine(); !letters.matches("[RBW]+"); letters = s.nextLine())
{
System.out.println("Invalid entry. Please enter the correct letters.");
}
System.out.println("Thank you");
char[] sort2 = letters.toCharArray();
Arrays.sort(sort2);
String sorted = new String(sort2);
System.out.println("Here are your letters sorted:" +sorted);

You could do something like this. Have three different StringBuilders and add each letter to them accordingly. Then concatenate them in the right order when its done looping through the letters.
StringBuilder r = new StringBuilder();
StringBuilder w = new StringBuilder();
StringBuilder b = new StringBuilder();
for (char c : letters.toCharArray()){
switch(c){
case 'R' : r.append(c); break;
case 'B' : b.append(c); break;
case 'W' : w.append(c); break;
}
}
String sorted = r.toString() + b.toString() + w.toString();
System.out.println("Here are your letters sorted:" + sorted);

Arrays.sort(char[]) uses natural ordering, so you'll get Bs then Rs then Ws.
If you want an other sort order you have to implement your own Comparator and use Arrays.sort(T[], Comparator). Therefore you have to convert it to an Object array.
Arrays.sort(sort2, new Comparator<Char>() {
public int compare(Char o1, Char o2) {
if (Char.valueOf("R").equals(o1)) {
if (Char.valueOf("R").equals(o2)) {
return 0;
} else {
return -1;
}
} else if (Char.valueOf("B").equals(o1)) {
....
}
});

Related

Asking user to enter specific number of strings then adding each string to array?

New to java. I need to ask the user the number of strings (consisting only of upper and lowercase letters, spaces, and numbers) they want to input. These strings need to be stored in an array. Then I created a boolean method to be able to tell if those strings are palindromic (ignoring spaces and cases). If it is palindromic then I add to the result list to print later on. I am confused on how to ask the user to input that exact amount of strings and how to check each individual string. I must use StringBuilder. This is what I have so far (it's kind of a mess, sorry). I feel like I'm using the StringBuilder/array wrong, how can I fix this?
public class Palindromes {
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder(numOfStrings);
for(int n=0; n < paliString; n++){
paliString[n] = scan.nextLine();
scan.nextLine();
String[] stringPali = new String[numOfStrings];
StringBuilder str = paliString;
if(isPali(userString)){
paliString = append.userString;
}
System.out.println("The palindromes are: " + userString ";");
}
static boolean isPali(String userString) {
int l = 0;
int h = userString.length() - 1;
// Lowercase string
userString = userString.toLowerCase();
// Compares character until they are equal
while (l <= h) {
char getAtl = userString.charAt(l);
char getAth = userString.charAt(h);
// If there is another symbol in left
// of sentence
if (!(getAtl >= 'a' && getAtl <= 'z'))
l++;
// If there is another symbol in right
// of sentence
else if (!(getAth >= 'a' && getAth <= 'z'))
h--;
// If characters are equal
else if (getAtl == getAth) {
l++;
h--;
}
// If characters are not equal then
// sentence is not palindrome
else
return false;
}
// Returns true if sentence is palindrome
return true;
}
}
SAMPLE RESULT:
Enter the number of strings: 8
Enter the strings:
Race Car
Mountain Dew
BATMAN
Taco Cat
Stressed Desserts
Is Mayonnaise an instrument
swap paws
A Toyotas a Toyota
The palindromes are: Race Car; Taco Cat; Stressed Desserts; swap paws; A Toyotas a Toyota
As I think the best way to answer this is to help you learn in small steps, I tried to stick with your initial idea on how to solve this and edited your main method with minimal changes.
This one does the trick.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder();
for (int n = 0; n < numOfStrings; n++) {
String userString = scan.nextLine();
if (isPali(userString)) {
if (paliString.length() > 0) {
paliString.append("; ");
}
paliString.append(userString);
}
}
System.out.println("The palindromes are: " + paliString);
}
Key changes:
I added scan.nextLine(); right after reading the number of strings. This handles the newline you get when the user hits enter.
You don't need to initialize the StringBuilder with numOfStrings. This just preallocates the size of the StringBuilder in characters. Not the number of strings. Either way, it's not necessary. StringBuilder grows as needed.
I suggest you inspect what I did inside the for-loop. This was the biggest mess and changed significantly.
Last but not least: Writing the result needs to be outside of the for-loop, after all palindromes have been added to the StringBuilder.
Edit
Based on your comment, in this next iteration, I changed the usage of StringBuilder to the usage of an ArrayList. (Which is something completely different)
I am using it here because Lists in Java grow on demand. And since the number of palindromes is probably not equal to the number of input strings, this is the way to go. To really assign it to an array, one could always call String[] paliStringsArray = paliStrings.toArray(new String[]{}); but as ArrayLists already use an underlying array and are not necessary to to generate the output you want, I didn't put it into the new version.
Please compare the differences of this step to the previous version. I also added this String.join("; ", paliStrings) part, which creates the output you want.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
List<String> paliStrings = new ArrayList<>();
for (int n = 0; n < numOfStrings; n++) {
String userString = scan.nextLine();
if (isPali(userString)) {
paliStrings.add(userString);
}
}
System.out.println("The palindromes are: " + String.join("; ", paliStrings));
}
And now to the last step. Arvind Kumar Avinash actually solved a part that I also missed in the initial question. (I'll read more carefully in the future). He was validating the user input. So for the last iteration, I added his validation code in a modified way. I put it into a method as I think that makes things clearer and gets rid of the necessity of a the boolean valid variable.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
List<String> paliStrings = new ArrayList<>();
for (int n = 0; n < numOfStrings; n++) {
String userString = readNextLine(scan);
if (isPali(userString)) {
paliStrings.add(userString);
}
}
System.out.println("The palindromes are: " + String.join("; ", paliStrings));
}
static String readNextLine(Scanner scanner) {
while (true) {
String userString = scanner.nextLine();
if (userString.matches("[A-Za-z0-9 ]+")) {
return userString;
} else {
System.out.println("Error: invalid input.");
}
}
}
I need to ask the user the number of strings (consisting only of upper
and lowercase letters, spaces, and numbers) they want to input. These
strings need to be stored in an array.
I have done the above part of your question. I hope, this will give you direction to move forward.
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("Enter the number of strings: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
String input;
for (int i = 0; i < numOfStrings; i++) {
do {
valid = true;
System.out.print("Enter a string consisting of only letters and digits: ");
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9 ]+")) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
stringPali[i] = input;
}
}
}
A sample run:
Enter the number of strings: a
Error: invalid input.
Enter the number of strings: 3
Enter a string consisting of only letters and digits: Arvind
Enter a string consisting of only letters and digits: Kumar Avinash
Enter a string consisting of only letters and digits: !#£$%^&*()_+
Error: invalid input.
Enter a string consisting of only letters and digits: Hello #
Error: invalid input.
Enter a string consisting of only letters and digits: Hello 123
Feel free to comment in case of any doubt/issue.
Wish you all the best!
[Update]
Based on your request, I have posted the following update which asks for the strings only once and then allows the user to enter all the strings one-by-one:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("Enter the number of strings: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
String input;
System.out.println("Enter " + numOfStrings + " strings consisting of only letters and digits: ");
for (int i = 0; i < numOfStrings; i++) {
do {
valid = true;
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9 ]+")) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
stringPali[i] = input;
}
}
}
A sample run:
Enter the number of strings: 3
Enter 3 strings consisting of only letters and digits:
Arvind
Kumar
He$ll0
Error: invalid input.
Avinash
Feel free to comment in case of any doubt.

How can I replace certain characters within a String in Java?

I have a program that reads an input (a String) and prints that String reversed. Now, I need to read through the reversed String and replace all of the "A"s with "T"s, the "T"s with "A"s, the "G"s with "C"s and the "C"s to "G"s. So basically, the "complement". I tried to use multiple lines with a replace function but once the "A"s are turned into "T"s, it will replace all of those into "A"s so there are no "T"s at all. How can I replace the characters so that they do not override each other?
Here is my code if it helps! I don't have any functions to get the "complement" yet, but here is what I'm working with.
import java.util.*;
public class DNA {
public static void main(String[] args)
{
System.out.println("Please input a DNA sequence: ");
Scanner read;
read = new Scanner(System.in);
String input = read.next();
String reverse="";
for(int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
System.out.println("Here is the reversed sequence: ");
System.out.println(reverse);
}
}
You can convert your reverse string to a char array like this:
char[] charArr = reverse.toCharArray();
Then you can iterate through it and change the characters that you want:
for(int i = 0; i < charArr.length; i++){
if(charArr[i] == 'A'){
charArr[i] = 't';
}
}
At the end you can convert the char array back to a string like this:
String str = new String(charArr);
Here is a code sample that you can try:
import java.util.Scanner;
class DNA {
public static void main(String[] args)
{
System.out.println("Please input a DNA sequence: ");
Scanner read = new Scanner(System.in);
String input = read.next();
String reverse="";
StringBuilder sb = new StringBuilder();
for(int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
for (char c: input.toCharArray()) { // user 'reverse' to operate on reversed string
switch (c) {
case 'A' : sb.append('T'); break;
case 'T' : sb.append('A'); break;
case 'G' : sb.append('C'); break;
case 'C' : sb.append('G'); break;
default : sb.append(""); break; // handle you're exceptions here
}
}
System.out.println("x: " + sb);
System.out.println("Here is the reversed sequence: ");
System.out.println(reverse);
read.close();
}}
Well, switch-case is a kind of mapping technique which will map your case (as key) with it's values. In this case:
I am replacing 'A' with 'T' where the string contains 'A' by appending into the StringBuilder (to create a new string) and then break; which is a mandatory statement for single time execution only.
And the default keyword is for default case, which means if all of the cases are unsatisfied to be executed then the default case is called, you can do whatever you want to do by default if no case, condition matched.
Well, for your last question, You can make it generic if the problem states some pattern; if not you, unfortunately have to do it manually.
Use the replace method, but change your values to a "temporary" character. https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)
Replace T -> x
Replace A -> T
Replace x -> A
Repeat for all your pairs.

Pig Latin String Encryption

I am writing a program that takes a string, splits it into words, converts the words into pig latin, and then returns the result string. I have it working to a certain point.
For example if I enter these words that do not start with a vowel into the program I get:
pig -> igpay
trash -> rashtay
duck -> uckday
(for words that do not start with vowels, they have their first letter removed, added to the end of the word along with "ay")
It also works when the word starts with a vowel (just take the word and add "yay" to the end).
For example if I enter these words into the program I get:
eat -> eatyay
areyay -> areyay
omelet -> omeletyay
Now the issue I am having is if I combine 2 words, one that starts with a vowel and one that doesn't, it prints out both like they both start with vowels.
For example if I enter these words into the program I get:
pig -> pigyay (should be igpay)
eat -> eatyay (correct)
It might be worth mentioning that the methods "isVowel" & "pigLatinEncrypt" are required to have in this program. Please disregard the other methods that are in the program.
public static void main(String[] args) {
// TODO code application logic here
String input, message;
int ans1, ans2, key;
input = JOptionPane.showInputDialog("1. to decrypt a message\n2. to encrypt a message");
ans1 = Integer.parseInt(input);
input = JOptionPane.showInputDialog("1. for an entire message reversal encryption\n"
+ "2. for a Pig-Latin encryption\n3. for a simple Caesar style encryption");
ans2 = Integer.parseInt(input);
if (ans2 == 3) {
input = JOptionPane.showInputDialog("Please enter a key for encryption");
key = Integer.parseInt(input);
}
input = JOptionPane.showInputDialog("Please enter the message to encrypt or decrypt");
message = input;
if (ans2 == 1) {
reverseEncryptandDecrypt(message);
}
if (ans2 == 2) {
String[] words = message.split(" ");
if (ans1 == 2) {
boolean isVowel = isVowel(words);
pigLatinEncrypt(words, isVowel);
}
if (ans1 == 1) {
pigLatinDecrypt(message);
}
}
}
public static void reverseEncryptandDecrypt(String message) {
char[] stringToCharArray = message.toCharArray();
System.out.print("You entered the message: ");
for (char c : stringToCharArray) {
System.out.print(c);
}
int i = stringToCharArray.length - 1, j = 0;
char[] reverse = new char[stringToCharArray.length];
while (i >= 0) {
reverse[j] = stringToCharArray[i];
i--;
j++;
}
System.out.print("\n\nThe result is: ");
for (char c : reverse) {
System.out.print(c);
}
System.out.println();
}
public static void pigLatinEncrypt(String[] words, boolean isVowel) {
for (String word : words) {
if (isVowel == true) {
System.out.print(word + "yay ");
} else {
System.out.print(word.substring(1) + word.substring(0, 1) + "ay ");
}
}
}
public static boolean isVowel(String[] words) {
boolean isVowel = false;
for (String word : words) {
if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o")
|| word.startsWith("u")) {
isVowel = true;
}
}
return isVowel;
}
}
This method:
public static void pigLatinEncrypt(String[] words, boolean isVowel)
takes an array of words and a single isVowel boolean. Thus, if there is more than one word, and some, but not all, of them begin with vowels, there's no way to tell the method that.
You'll need to change the method definition. Either it should take only one word String (simplest), or it needs to take an array of isVowel booleans that correspond to the array of word
Edit: When I wrote this, I didn't look carefully at the rest of your code. But the isVowel method has the same problem: it takes an array of words, but returns a single boolean. This can't work, for the same reason--if some of the words start with vowels and some don't, what would the method return?
If you can make the isVowel method take a single String argument, that would be simplest. Then you'd call it multiple times. If you want to make isVowel return a boolean[], the method would do something like
boolean[] result = new boolean[words.length];
to create an array of boolean that has the same number of elements as words.

Creating array with unknown elements by Input them

I know this isn't something you are supposed to do yet but I'm still trying to figure out a way to run this loop, an letting the arr[i] inside it "know" about the rise of the number of elements in the array (which I declare outside of the loop because I don't want it to make a new one each time).
int counter=1, note=0;
System.out.println("Please enter characters, -1 to stop: ");
do {
char[] arr= new char[counter];
for (int i=0;i<=counter;i++){
arr[i] = s.next().charAt(0);
if (arr[i]==-1){
note = -1;
break;
}
++counter;
}
} while (note>=0);
From your much clearer comment, this is an example main method.
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Input
int amt = 0; // Amount of chars received
List<Character> chars = new ArrayList<>(); // ArrayList is easier for now
while (input.hasNext()) { // Grabs Strings separated by whitespaces
String token = input.next(); // Grab token
if (token.equals("-1")) {
break; // End if -1 is received
} else if (token.length() != 1) {
throw new IllegalArgumentException("Token not one char: " + token);
// It seems you want only chars - this handles wrong input
} else {
chars.add(token.charAt(0)); // Adds the character to the list
amt++; // Increment amt
}
}
char[] array = new char[amt]; // Converting to an array
for (int i = 0; i < amt; i++) {
array[i] = chars.get(i); // Copies chars into array
}
System.out.println(Arrays.toString(array)); // Handle data here
}
I hope that this is correct. An input of a b c d -1 leads to an output of [a, b, c, d].
If you use the Input String size check I think as you will be resolved.
int counter=0, note=0;
System.out.println("Please enter characters, -1 to stop: ");
String input=s.nextLine();
counter=input.length();
char[] arr= new char[counter];
for (int i=0;i<counter;i++){
arr[i] = input.charAt(i);
}
and If you are using the ArrayList rather than Array is no need to worry about the size.
ArrayList is effective flexable data
cause using add function.

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

Categories

Resources