Count letters in a string Java - java

I'm doing an assignment where I'll have to code a program to read in a string from user and print out the letters in the string with number of occurrences. E.g. "Hello world" in which it should print out "h=1 e=1 l=3 o=2 ... etc.", but mine only write "hello world" and the amount of letters in total. I can't use the hashmap function, only arrays. Can someone give me a hint or two on how to proceed from the written code below to get my preferred function? I don't understand exactly how to save the written input in array.
Here's my code so far.
public class CountLetters {
public static void main( String[] args ) {
String input = JOptionPane.showInputDialog("Write a sentence." );
int amount = 0;
String output = "Amount of letters:\n";
for ( int i = 0; i < input.length(); i++ ) {
char letter = input.charAt(i);
amount++;
output = input;
}
output += "\n" + amount;
JOptionPane.showMessageDialog( null, output,
"Letters", JOptionPane.PLAIN_MESSAGE );
}
}

You don't need 26 switch cases. Just use simple code to count letter:
String input = userInput.toLowerCase();// Make your input toLowerCase.
int[] alphabetArray = new int[26];
for ( int i = 0; i < input.length(); i++ ) {
char ch= input.charAt(i);
int value = (int) ch;
if (value >= 97 && value <= 122){
alphabetArray[ch-'a']++;
}
}
After done count operation, than show your result as:
for (int i = 0; i < alphabetArray.length; i++) {
if(alphabetArray[i]>0){
char ch = (char) (i+97);
System.out.println(ch +" : "+alphabetArray[i]); //Show the result.
}
}

Create an integer array of length 26.
Iterate each character of the string, incrementing the value stored in the array associated with each character.
The index in the array for each character is calculated by x - 'a' for lower case characters and x - 'A' for upper case characters, where x is the particular character.

You can create an Array which first element will represent 'a', second 'b', etc. If you need distinction between lower and upper cases than you can add it at the end. This array will have all values equals 0 at the beginning.
Then you iterate through your sentence and you increment required values on the array.
At the end you print all values that are > 0. Simple?
Let me know if you need more help

No you should not create an array of 26. This will break if the string contains unexpected characters. (ä, ö, ü anyone?)
As I pointed out im my comment use a Map. This will work forr all posible characters out there.

import java.io.*;
public class CharCount {
public static void main(String[] args) throws IOException
{
int i,j=0,repeat=0;
String output="",input;
char c=' ';
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter name ");
input=br.readLine();
System.out.println("entered String ->\""+input+"\"");
input=input.toLowerCase();
for(i=0;i<input.length();i++)
{
for(j=0;j<output.length();j++)
{
if(input.charAt(i)==output.charAt(j) || input.charAt(i)==c)
{
repeat=1;
break;
}
}
if(repeat!=1)
{
output=output+input.charAt(i);
}
repeat=0;
}
System.out.println("non-reepeated chars in name ->\""+output+"\"");
int count[]=new int[output.length()];
for(i=0;i<output.length();i++)
{
for(j=0;j<input.length();j++)
{
if(output.charAt(i)==input.charAt(j))
count[i]=count[i]+1;
}
}
for(i=0;i<output.length();i++)
System.out.println(output.charAt(i)+"- "+count[i]);
}
}

Related

What is the best way to replace a letter with the letter following it in the alphabet in Java?

I'm a programming newbie and I am doing a coderbyte exercise that says "
Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a)"
i'm thinking of the following methods:
declare a string called "abcdefghijklmnopqrstuvxyz" and compare each string's char index position with the alphabet's index position, and then just bring the alphabet char that is located at the i+1 index location. But I don't know how it would work from z to a.
I've seen some techniques using ASCII values for every char but I've never done that before and not sure how it works
convert the given string into a char[] array, but then I'm not sure how I would tell the system to get me the next alphabet char
What would be the easiest way to do this?
EDIT
this is my code so far, but it doesn't work.
import java.util.*;
import java.io.*;
class Main {
public static String LetterChanges(String str) {
// code goes here
String alphabet = "abcdefghijklmnopqrstuvwxyz";
String newWord = "";
for (int i = 0; i < str.length(); i++){
for (int j = 0; j < alphabet.length(); i++){
if (str[i] == alphabet[i]){
if (alphabet[i+1].isVowel()){
newWord = newWord + toUpperCase(alphabet[i+1]);
}
else{
newWord = newWord + alphabet[i+1];
}
}
}
}
return str;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterChanges(s.nextLine()));
}
}
Can't I ask for the index position of a Char that is a part of a String? in C I could do that.
Other than that not sure why it doesn't work.
I would definitely go with method 1.
I believe what you're looking for is the indexOf method on a String.
First of, I would create a method that given a character finds the next letter in the alphabet and return that. This could be done by finding the letter in your alphabet string and then fetch the letter at index+1. As you also pointed out you would need to take care of the edge case to turn 'z' into 'a', could by done with an if-statement or by having an extra letter 'a' at the end of your alphabet string.
Now all that remains to do is create a loop that runs over all characters in the message and calls the previously made method on that character and constuct a new string with the output.
Hope this helps you figure out a solution.
Assuming that there would be only lower case English letters in the given String the most performant way would be to add +1 to every character, and use either if-statement checking whethe the initial character was z or use the modulo operator % as #sp00m has pointed out in the comment.
Performing a search in the alphabetic string (option 1 in your list) is redundant, as well extracting array char[] from the given string (option 3).
Checking the edge case:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = str.charAt(i);
if (next == 'z') result.append('a'); // checking the edge case
else result.append((char) (next + 1));
}
return result.toString();
}
Applying modulo operator:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = (char) ((str.charAt(i) - 'a' + 1) % 26 + 'a');
result.append(next);
}
return result.toString();
}
main()
public static void main(String[] args) {
System.out.println(shiftLetters("abc"));
System.out.println(shiftLetters("wxyz"));
}
Output:
bcd // "abc"
xyza // "wxyz"

How to reverse a String after a comma and then print the 1st half of the String Java

For example String grdwe,erwd becomes dwregrdwe
I have most of the code I just have trouble accessing all of ch1 and ch2 in my code after my for loop in my method I think I have to add all the elements to ch1 and ch2 into two separate arrays of characters but I wouldn't know what to initially initialize the array to it only reads 1 element I want to access all elements and then concat them. I'm stumped.
And I'd prefer to avoid Stringbuilder if possible
public class reverseStringAfterAComma{
public void reverseMethod(String word){
char ch1 = ' ';
char ch2 = ' ';
for(int a=0; a<word.length(); a++)
{
if(word.charAt(a)==',')
{
for(int i=word.length()-1; i>a; i--)
{
ch1 = word.charAt(i);
System.out.print(ch1);
}
for (int j=0; j<a; j++)
{
ch2 = word.charAt(j);
System.out.print(ch2);
}
}
}
//System.out.print("\n"+ch1);
//System.out.print("\n"+ch2);
}
public static void main(String []args){
reverseStringAfterAComma rsac = new reverseStringAfterAComma();
String str="grdwe,erwd";
rsac.reverseMethod(str);
}
}
You can use string builder as described here:
First split the string using:
String[] splitString = yourString.split(",");
Then reverse the second part of the string using this:
splitString[1] = new StringBuilder(splitString[1]).reverse().toString();
then append the two sections like so:
String final = splitString[1] + splitString[0];
And if you want to print it just do:
System.out.print(final);
The final code would be:
String[] splitString = yourString.split(",");
splitString[1] = new StringBuilder(splitString[1]).reverse().toString();
String final = splitString[1] + splitString[0];
System.out.print(final);
Then, since you are using stringbuilder all you need to do extra, is import it by putting this at the top of your code:
import java.lang.StringBuilder;
It appears you currently have working code, but are looking to print/save the value outside of the for loops. Just set a variable before you enter the loops, and concatenate the chars in each loop:
String result = "";
for (int a = 0; a < word.length(); a++) {
if (word.charAt(a) == ',') {
for (int i = word.length() - 1; i > a; i--) {
ch1 = word.charAt(i);
result += ch1;
}
for (int j = 0; j < a; j++) {
ch2 = word.charAt(j);
result += ch2;
}
}
}
System.out.println(result);
Demo
Let propose a solution that doesn't use a StringBuilder
You should knoz there is no correct reason not to use that class since this is well tested
The first step would be to split your String on the first comma found (I assumed, in case there is more than one, that the rest are part of the text to reverse). To do that, we can you String.split(String regex, int limit).
The limit is define like this
If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n and the array's last entry will contain all input beyond the last matched delimiter.
If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Example :
"foobar".split(",", 2) // {"foobar"}
"foo,bar".split(",", 2) // {"foo", "bar"}
"foo,bar,far".split(",", 2) // {"foo", "bar,far"}
So this could be used at our advantage here :
String text = "Jake, ma I ,dlrow olleh";
String[] splittedText = text.split( ",", 2 ); //will give a maximum of a 2 length array
Know, we just need to reverse the second array if it exists, using the simplest algorithm.
String result;
if ( splittedText.length == 2 ) { //A comma was found
char[] toReverse = splittedText[1].toCharArray(); //get the char array to revese
int start = 0;
int end = toReverse.length - 1;
while ( start < end ) { //iterate until needed
char tmp = toReverse[start];
toReverse[start] = toReverse[end];
toReverse[end] = tmp;
start++; //step forward
end--; //step back
}
result = new String( toReverse ) + splittedText[0];
}
This was the part that should be done with a StringBuilder using
if ( splittedText.length == 2 ){
result = new StringBuilder(splittedText[1]).reverse().toString() + splittedText[0];
}
And if there is only one cell, the result is the same as the original text
else { //No comma found, just take the original text
result = text;
}
Then we just need to print the result
System.out.println( result );
hello world, I am Jake

ROT13 in Java doesn´t want to work properly

At some point I have trouble programming ROT13 in Java. So the User shall write whatever he wants and the programm should rewrite it in ROT13. So here´s my programm until now:
import java.io.*;
public class rot13
{
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed
String key [] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
String keyA [] = {"N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A","B","C","D","E","F","G","H","I","J","K","L","M"};
String letter;
System.out.println("Enter a phrase:");
String phrase = myInput.readLine();
int y = 0, i = 0;
while ( y <= phrase.length()){
letter = Character.toString(phrase.charAt(y));
while(i <= y){
if (letter != key[i]){
keyA [i] = keyA[i];
}
i++;
}
System.out.println(keyA [i]);
y++;
}
}
}
The problem is the following:
It only does go for a few letters, but stops working after like 3 lines or rather after 3 latters and puts up errors which are:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(Unknown Source)
at rot13.main(rot13.java:19)
I´ve tried different words, but it keeps printing out the same problem. Does anyone knows how to fix it or at least a way to do it more proberly?
Thanks in advance!!
Why it doesn't work
import java.io.*;
public class rot13
{
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed
String key [] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
String keyA [] = {"N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A","B","C","D","E","F","G","H","I","J","K","L","M"};
String letter;
System.out.println("Enter a phrase:");
String phrase = myInput.readLine();
int y = 0, i = 0;
while ( y <= phrase.length()){
letter = Character.toString(phrase.charAt(y));
//Each time you go throught the first loop, you are comparing your actual position in the string and i
//But as you don't reset i back to 0, you only try to compare your previous index and your actual index : if y == 3, so i takes only the values 2 and 3
//Moreover, when y > 26, you try to access the key array outside of its bounds
while(i <= y){
// letter is a string so you should be using equals
if (letter != key[i]){
// You are putting the value at the i index in the i index, so you do basically nothing with this line
keyA [i] = keyA[i];
}
i++;
}
System.out.println(keyA [i]);
y++;
}
}
}
Alternative
Here's a solution you can use :
import java.io.*;
public class rot13 {
public static void main(String[] args) throws IOException {
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));// Buffered Reader reads the number inputed
System.out.println("Enter a phrase:");
String input = myInput.readLine();
//We loop through every char in the string
for (char c : input.toCharArray()) {
//We check if the character is a letter, so we don't add the offset to special characters like space or dot
if (Character.isAlphabetic(c)) {
//Here we get the lower case version of the char and remove it 97, which is the ascii value of 'a'
//With this, we are mapping letters from a to z to numbers from 0 to 25
char lowerChar = (char) (Character.toLowerCase(c) - 97);
//We add the offset of 13
lowerChar += 13;
//We then use the modulo to move numbers higher than 15 back to the beginning
lowerChar %= 26;
//We finally come back to the ascii value of our lower case char
lowerChar += 97;
System.out.print(Character.isUpperCase(c) ? Character.toUpperCase(lowerChar) : lowerChar);
} else {
//If it's not a letter, we just print the char
System.out.print(c);
}
}
//We don't forget to close our BuffererReader
myInput.close();
}
}
This is a described version but you can shorten it by doing all the char operations on one line

How do I store these printed letters into an array?

Right now this program prints out the alphabet (a-z) however I want to take those letters and store each one in the array called leta, how do i do that?
public class Arrayofhope {
public static void main (String[]args) {
char []leta = new char[26];
char letter = (char)65;
char lettter=(char)90;
for (int i = letter;i<=lettter;i++ ) {
System.out.print((char)i);
}
}
}
This is almost a "syntax" type question, but it's also tricky enough that there's some value to pointing out how it works.
class Arrayofhope
{
public static void main( String[] args )
{
char[] leta = new char[ 26 ];
char letterA = 'a';
char letterZ = 'z';
for( int i = letterA; i <= letterZ; i++ ) {
System.out.print( (char) i );
leta[i-'a'] = (char)i;
}
}
}
Characters in single quotes are the same as integers of type char. You can assign them and do math on them. I think this makes the initial assignment of char letterA = 'a'; more clear than using the number 65.
And as mentioned you can do math with character types too. Note the aray index [i-'a'] is calculated so that 65 is subtracted from 65 for the first character, so that 'a' is stored in index 0, and proceeding up from there. This is kinda tricky but in the long run more clear, I think, and also easier than trying to program with an ASCII table in front of you.
public class Arrayofhope {
public static void main (String[]args) {
char []leta = new char[26];
char letter = (char)65;
char lettter=(char)90;
for (int i = letter,j=0;i<=lettter;i++,j++ ) {
let[j] = (char)i;
// If you don't want new variable you can do like below
let[i-65] = (char) i;
System.out.print((char)i);
}
}
}

Index value wont Increase after comparing two chars

I started this because I was totally bored but because of this error I have been sitting here since so long and finally decided to take this to stackOverFlow. Here is the code Which I wrote.
I was trying to print characters by skipping 1 index. But when there are duplicates I want to print a space which would differentitate words from big string.
Updated Question: Everything fixed except I cant increase I value more than 1. I commented it in below program. Please look at it.
Let me cut the chase and get to the point. I need this output " Vishnu Vardhan" from this String "aVeIwSjHaNgUaaVdAgRjDkHxAmN";
My only requirement is if the string has two same letters it has to print space. So "aVeIwSjHaNgU [aa] VdAgRjDkHxAmN" the aa in the brackets has to be replaced by space.
It has to be dynamic, if any char is repeated it has to print a space and jump to required next char and print it.
Here is the Updated program. Using help from one of the comments.
public class Decrypter {
public static void main(String[] args) {
String Text = "aVeIwSjHaNgUaaVdAgRjDkHxAmN";
char[] convertedText = Text.toCharArray();//converted string to char array
for (int i = 1; i < convertedText.length; i++) { //Looping it to print alternate chars
/* if the character at an index is same as the character at next index then
add a space and increase index value by 2 so I can print the required char*/
if (i + 1 < convertedText.length) {
if (Text.charAt(i) == Text.charAt(i + 1)) {
i++;// Increasing I value by 2 here will give me required output. Everything is perfect now
System.out.printf("%s ", convertedText[i]);
} else {
System.out.printf("%s", convertedText[i]);
i++;
}
}
}
}
}
Current output : VISHNUadgjkxm
Required output: VISHNU VARDHAN
i dont know if converting string to charArray is required but i hope this will do. comment below if you have questions open for revision.
String text = "aVeIwSjjHaNgUkkVarqddlhxn";
//this is the holder of your new processed text.
String newText = "";
//start of counter. it may start in any number depends on requirements.
int x = 0;
//loop while the x is lessthan the length of your string.
while(x < text.length()){
//check if the x + 1 is not equal to the length of your string to avoid StringIndexOutOfBoundsException
if((x+1) != text.length()){
//in this area it will check if the current char is the same on next index
if(text.charAt(x) == text.charAt(x+1)){
// this will concatenate/append the value of char with space
newText += text.charAt(x) +" ";
// this will increase the value of your x by 1 and at the bottom there are also x++ that will add 1 to your x so the total sum of x if (text.charAt(x) == text.charAt(x+1)) are true, will be 2.
x++;
}
}
newText += text.charAt(x);
x++;
}
System.out.println(newText);
output :
aVeIwSj jHaNgUk kVarqd dlhxn
if this is not what you looking for please kindly update your question.
Fixed:
/**
*
* #author Chintu
*/
public class Decrypter {
public static void main(String[] args) {
String Text = "aVeIwSjHaNgUkkVarqdlhxn";
char[] convertedText = Text.toCharArray();//converted string to char array
for (int i = 1; i < convertedText.length; i++) { //Looping it to print alternate chars
/* if the character at an index is same as the character at next index then
add a space and increase index value by 2 so I can print the required char*/
if (i+1 < convertedText.length) {
if (Text.charAt(i) == Text.charAt(i + 1)) {
i++;
System.out.printf("%s ",convertedText[i]);
}
}
System.out.printf("%s", convertedText[i]);
}
}
}
Fixed
public class Decrypter {
public static void main(String[] args) {
String Text = "aVeIwSjHaNgUaaVdAgRjDkHxAmN";
char[] convertedText = Text.toCharArray();//converted string to char array
for (int i = 0; i < convertedText.length; i++) { //Looping it to print alternate chars
/* if the character at an index is same as the character at next index then
add a space and increase index value by 2 so I can print the required char*/
if (i + 1 < convertedText.length) {
if (Text.charAt(i) == Text.charAt(i + 1)) {
i += 2;
System.out.printf(" %s", convertedText[i]);
} else {
i++;
System.out.printf("%s", convertedText[i]);
}
}
}
}
}
output: VISHNU VARDHAN

Categories

Resources