counting the alphabets from input - java

I need to write a code in java, which will take the input as a string from the user and will print the count of repetition of each alphabet. I Ihave written the code but not got the correct output.
input:ppooj
output:p1,o2,j1
My code is:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Hello");
System.out.println("ENTER ANY STRING");
Scanner sc= new Scanner(System.in);
String[] arr= new String [5];
for(int i=0; i<5 ;i++ )
{
arr[i]= sc.next();
// getting input
}
for ( int i=0;i<5;i++){
System.out.print(""+ arr[i]);
}
int count=1;
int rep=0;
int i=0;
for ( i=0;i<5;i++)
{
//traverse
System.out.println("in first loop" + ""+ arr[i]);
for(int k=i+1; k<5;k++)
{
System.out.println("" + arr[k]);
//matching with each and every one
if(arr[i]==arr[k])
{
count++;
System.out.println("got the match" + count);
}
}
System.out.println(arr[i]+count+",");
count=1;
}
}
}

You can follow these steps.
Read input.
split the input to characters. (You can get the char[] from String)
Iterate the char[] and you can use Map<Character,Integer> to store character vs number of occurrences.
Now your map contains all characters with occurrences.

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class AlphaCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string");
String str = sc.nextLine();
Map<Character, Integer> map = new HashMap<Character, Integer>();
char[] chArray = str.toCharArray();
for(char c : chArray){
if(map.containsKey(c)){
map.put(c, map.get(c)+1);
}
else{
map.put(c, 1);
}
}
for (Entry<Character, Integer> entry : map.entrySet())
{
System.out.print(entry.getKey() + "" + entry.getValue()+" ");
}
}
}

If you use only alphabets, try this approach
Take an array of size 26
Assign array with 0
let the index be the alphabet position like 0-a, 1-b ... 25-z
oop through the input string and increment the respective index position like
array[inputString.charAt(i)-'a']++;
Print the result accordingly

Use equals method to compare reference objects value. As sometimes it get struck in the heap. So, it is better to use equals method over "==" while comparing values of reference objects.
Array is a reference type object.
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Hello");
System.out.println("ENTER ANY STRING");
Scanner sc= new Scanner(System.in);
String[] arr= new String [5];
for(int i=0; i<5 ;i++ )
{
arr[i]= sc.next();
// getting input
}
for ( int i=0;i<5;i++){
System.out.print(""+ arr[i]);
}
int count=1;
int rep=0;
int i=0;
for ( i=0;i<5;i++)
{
//traverse
// System.out.println("in first loop" + ""+ arr[i]);
for(int k=i+1; k<5;k++)
{
// System.out.println("" + arr[k]);
//matching with each and every one
if(arr[i].equals(arr[k]))
{
count++;
System.out.println("got the match" + count);
}
}
System.out.println(arr[i]+count+",");
count=1;
}
}
}
Try this code. You can modify it as per your requirement in the application.

You can try Map with String as the key like this:
Map<String,Integer> map = new HashMap<String,Integer>();
// set value = 0 to characters from a-z.
for( int i = 'a'; i < 'z'; i++ ){
map.put(String.valueOf((char)i), 0);
}
// supposed you have this as your input array. This should be read from file.
String[] arr= {"p","p","o","o","j"};
// count the duplicated characters.
for(int i=0;i<arr.length;i++){
map.put(arr[i],map.get (arr[i])+1);
}
// remove duplicated characters in array.
List<String> list= new ArrayList<String>(new LinkedHashSet<String>(Arrays.asList(arr)));
// print result.
for (String string : list) {
System.out.print(string+map.get(string));
}

Related

Multiply single character by given number in String

I have one goal:
1) Multiply character in String n-times (character, String, n [int] - from user input)
Example:
User input1 (String) : future
User input2 (char) : u
User input3 (int) : 2
Output: fuutuure
First i tried with char[] array but IndexOutOfBoundsException brought me back to reality. Second try-StringBuilder but its not working aswell-empty result window. Should I use StringBuilder (and if answer is yes-how?) ? Or there is other, better solution.
Thank you for help.
package Basics.Strings;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Ex4 {
static String giveAWord() {
Scanner scanWord = new Scanner(System.in);
System.out.println("Give a word");
String word = scanWord.nextLine();
return word;
}
static char giveALetter() {
Scanner scanALetter = new Scanner(System.in);
System.out.println("Give a letter");
char let = scanALetter.next().charAt(0);
return let;
}
static int giveANumber() {
Scanner scanNumber = new Scanner(System.in);
System.out.println("Give a number");
int numb = scanNumber.nextInt();
return numb;
}
static String multiplyLetter(String word, char letter, int number) {
StringBuilder sb= new StringBuilder();
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i)==letter) {
sb.append(i*number);
}
}
return sb.toString();
}
public static void main(String[] args) {
String word = giveAWord();
char letter = giveALetter();
int number = giveANumber();
System.out.println(multiplyLetter(word, letter, number));
}
}
There are several things in your multiplyLetter method that would make it not work.
First, you have to initialise the StringBuilder using the word so:
StringBuilder sb = new StringBuilder(word) ;
Else, your StringBuilder will be empty.
Second, you should use the insert(int pos, char c) method, so you can specify where you want tthe character inserted.
And last, you can't just multiply a char and an int and get away with it. If you want to repeatedly insert a character, I think you should use a loop.
So, in summary, try:
StringBuilder sb= new StringBuilder(word);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i)==letter) {
for ( int j = 0 ; j < number ; j++ ) {
sb.insert(i, letter);
i++ ;
}
}
}
Notice I added i++ inside the loop, as sb.length() will increase with each character inserted.
Also, maybe someone more experienced can provide with a more efficient way than just using a loop.
If you are using at least Java 11 (eleven) then the following will work:
String word = "future";
String letter = "u";
int count = 2;
String replacement = letter.repeat(count);
String result = word.replace(letter, replacement);
Note that only method repeat(int) was added in Java 11.
Method replace(CharSequence, CharSequence) was added in Java 5
Java 8 functional way:
String alterString(String input, Character charMatch, int times) {
return input.chars()
.mapToObj(c -> (Character) c) // converting int to char
.flatMap(c -> {
if (c == charMatch) {
Character[] ca = new Character[times];
Arrays.fill(ca, c);
return Arrays.stream(ca); // stream of char c repeated 'times' times
}
return Stream.of(c);
})
.collect(
// following is the string collecting using StringBuilder form stream of characters
Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString,
);
);
}
A simple way to solve this problem is by using the following functions:
String#join
Collections#nCopies
String#replace
Demo:
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = kb.nextLine();
System.out.print("Enter the character: ");
String ch = kb.nextLine();
System.out.print("How many times to repeat?: ");
int n = kb.nextInt();
String result = str.replace(ch, String.join("", Collections.nCopies(n, ch)));
System.out.println("Result: " + result);
}
}
A sample run:
Enter the string: future
Enter the character: u
How many times to repeat?: 2
Result: fuutuure

Word Anagram not getting all user input

I am writing a program checking if n words are anagrams of the initially given word. It the word is an anagram it prints "yes", if it isn't - prints "no". It solves the problem correctly if I input all the data manually in the console. If I copy and paste the data it does not "see" the last line until I hit enter again. So it I paste the following input:
anagram
6
gramana
aaagrnm
anagra
margana
abc
xy
So I get only 5 yes-es and no-s and when I hit enter again I get the last no.
here is my code
import java.util.Scanner;
import java.util.Arrays;
public class WordAnagrams {
public static void anagramCheck (String x, String y) {
char[] initial= new char[x.length()];
for (int i=0; i<x.length(); i++) {
initial[i]=x.charAt(i);
}
Arrays.sort(initial);
char[] isAnagram = new char[y.length()];
for (int i=0; i<y.length(); i++) {
isAnagram[i]=y.charAt(i);
// System.out.println(isAnagram[i]);
}
Arrays.sort(isAnagram);
boolean same=Arrays.equals(initial, isAnagram);
if (same) {
System.out.println ("yes");
}
else {
System.out.println ("no");
}
// return answer;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String word = input.nextLine();
int n = Integer.parseInt(input.nextLine());
String anagram=""; // input.nextLine();
// int counter=0;
System.out.println();
/* while (counter<n+1) {
anagram=input.nextLine();
anagramCheck(word, anagram);
// anagram=input.nextLine();
counter++;
}*/
for (int i=0; i<=n; i++) {
anagram=input.nextLine();
anagramCheck(word, anagram);
// anagram=input.nextLine();
// System.out.println(answers[i]);
}
System.out.println();
}
}
The issue is that when you copy paste the input, the last word have no '\n' at the end so the scanner doesn't read this as a line until you press ENTER.
So what I can propose is:
1) Use a File for an Input
Or 2) Use InputStreamReader to fetch from the console. Here is some code to do it:
`
public static void main(String[] args) throws IOException {
char buffer[] = new char[512];
InputStreamReader input = new InputStreamReader(System.in);
input.read(buffer,0,512);
String data[] = (new String(buffer)).split("\n");
}
`
It give you a list of strings at the end. PS: Your loop "for(int i =0;i<=n;i++)" is looping 7 times with n = 6.
#kalina199
You could also shorten your code a bit to save yourself from defining a method to check the input from the console.
I did it by splitting the console input into a String array using a simple regex and immediately sorted it.
Then my loop does a simple check to compare the new user input to the original word by their lengths and if that doesn't match you just print out "no" and continue with the next word.
Here's my code:
package bg.Cholakov;
import java.util.Arrays;
import java.util.Scanner;
public class Anagram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] initWord = scanner.nextLine().split("");
Arrays.sort(initWord);
int num = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < num; i++) {
String[] testWord = scanner.nextLine().split("");
Arrays.sort(testWord);
if (!(initWord.length == testWord.length)) {
System.out.println("no");
} else if (initWord[i].equals(testWord[i])) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
}

Java program of returning alphabets that a word is made of

I am trying to understand how pieces of code are contributing the program in java. So the program is supposed to take input from user for a word and then the output is printing the alphabets that the user inputted word is made of. The program is running fine but I need help in interpreting what the for loops are doing. Thank you!
import java.util.Scanner;
public class J0307_search {
public static void main(String[] args) {
String str1;
int count;
char[] arr1=new char[40];
Scanner s=new Scanner (System.in);
System.out.print("input a string:");
str1=s.nextLine();
arr1[0]=str1.charAt(0);
System.out.print(arr1[0]+"");
for (int i=1; i<str1.length();i++) {
count=0;
for (int j=0;j<i;j++) {
if (str1.charAt(i)==str1.charAt(j)) {
count++;
}
}
if (count<1) {
arr1[i]=str1.charAt(i);
System.out.print(arr1[i]+"");
}
}
System.out.print(" : only made up of these alphabets");
s.close();
}
}
I change code and add explain.
boolean behindExist;
for (int i=1; i<str1.length(); i++) {//loop for all character in string
behindExist = false;
for (int j=0; j < i; j++) {
//check same character is exist before now char
//Ex) if (i = 3), check
//str1.charAt(3) == str1.charAt(0);
//str1.charAt(3) == str1.charAt(1);
//str1.charAt(3) == str1.charAt(2);
if (str1.charAt(i)==str1.charAt(j)) {
behindExist = true;
}
}
if (!behindExist) {//if not behindExist
arr1[i]=str1.charAt(i);//add to arr1
System.out.print(arr1[i]+"");//and print character
}
}
And, this is my code.
Scanner sc = new Scanner(System.in);
System.out.print("input a string : ");
String input = sc.nextLine();
for(int charCode : input.chars().distinct().toArray()) {
System.out.print((char)charCode);
}
System.out.print(" : only made up of these alphabets");
sc.close();
Short. I love it. I hope this can be help. :)
Can we use something as simple as this? The Set will contain unique characters that make up the word.
char[] charArr = str1.toCharArray();
Set<Character> charSet = new HashSet();
for(char c: charArr){
charSet.add(c);
}
Why to complex the problem.
Try to use features of collection in java.
something like this:-
Set<Character> set = new HashSet(Arrays.asList(str1.toCharArray()));

swapping two letters in an unknown string in java

i am writing a program that must scramble a word. First I read in the word backwards using .reverse. Then I turned the string into a charArray.I am suppose to create a for loop to figure out if the First letter is "A" and if it is then i have to see if the next letter is not an "A". if its not then i am suppose to swap the two letters. If any of the two letters have a;ready been swapped than they cannot be swapped again.
Some examples are
Input: “TAN” Output: “ATN”
Input: “ALACTRIC” Output:“AALCTRIC”
Input: "Fork" Output:"Fork"
Here is my code so far: i cannot figure out what to put in the for loop. Thank you!
import java.util.Scanner;
public class scrambleWordRetry {
public static void main(String[] args)
{
}
public static String scramble( Random random, String inputString)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a word to scramble.");
inputString = scan.nextLine();
char a[] = inputString.toCharArray();
for( int i=0 ; i<a.length-1 ; i++ )
{
}
return inputString;
}
}
I hope this code is useful for you
Scanner x = new Scanner(System.in);
String str = x.next();
System.out.println("Before Swapping" + str);
str = scramble(str);
System.out.println("After Swapping " + str);
}
public static String scramble(String inputString) {
char s[] = inputString.toCharArray();
for (int i = 1; i < s.length; i++) {
if (s[i] == 'A' || s[i] == 'a') {
char temp = s[i - 1];
s[i - 1] = s[i];
s[i] = temp;
}
}
return new String(s);
}
then if you input 'ALACTRIC' the output will be 'AALCTRIC',
'Tan = aTn',
'fork = fork'.

ArrayList and strings

I have this question Write a static method which takes an ArrayList of Strings and an integer and changes the ArrayList destructively to remove all Strings whose length is less than the integer argument. i have this code so far could someone explain where I'm going wrong. it compiles but it doesn't remove any strings from the array list.
import java.util.*;
public class q4
// Shows adding a string after all occurrences of a string
// constructively in an ArrayList
{
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
ArrayList<String> a = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<words.length;j++)
{
String b =a.get(j);
if(b.length()<len)
{
a.remove(j);
}
}
System.out.println("The ArrayList is "+a);
}
}
When you remove an item of the ArrayList be sure to decrement "j". Also, although it is not common, set the for-condition to j < a.size(). Otherwise create a separate variable to store the size before the loop and then decrement it as well.
The following code should work.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
ArrayList<String> a = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<a.size(); j++)
{
String b =a.get(j);
if(b.length()<len)
{
a.remove(j);
j--;
}
}
System.out.println("The ArrayList is "+a);
}
You traverse the list from left to right and remove items as you go along. This causes a problem when removing multiple items, because the indices don't match any more.
This can be fixed quite easily by traversing the list from end to begin, instead of from begin to end.
Because now, if you remove an item, this doesn't affect the items to be removed later on:
for (int j = words.length - 1; j >= 0; j--)
import java.util.*;
public class q4
// Shows adding a string after all occurrences of a string
// constructively in an ArrayList
{
public static ArrayList<String> a;
public static ArrayList<String> presenter;
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
a = new ArrayList<String>();
presenter = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<words.length;j++)
{
String b =a.get(j);
if((b.length()<len))
{
//do nothing
}
else
{
presenter.add(a.get(j));
}
}
System.out.print("The ArrayList is " + presenter);
}
}
This is an alternative since you said the other codes didn't work, I simply transferred the "Good" data to another arraylist and printed out that one.

Categories