I need help on my code in Java.
This is the problem :
Example input : AaaaaAa
Output : A appears 7.
The problem is I need it to ignore cases.
Please help me, my code works fine, except that it doesn't ignore cases.
import java.io.*;
public class letter_bmp{
public static BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
public static void main(String[] args) throws Exception
{
String string1;
String pick;
String ans;
do
{
int count=0;
System.out.print("En taro Adun, Executor! Input desired string : ");
string1 = input.readLine();
System.out.print("Now, Executor...which character shall I choose : ");
pick = input.readLine();
for(int counter = 0; counter < string1.length(); counter++)
{
if(pick.charAt(0) == string1.charAt(counter))
count++;
}
System.out.print("Executor...you picked '" + pick + "' it is used " + count + " times in the word "+string1+".");
System.out.println("\nWould you like to try again, Executor? (Yes/No): ");
ans = input.readLine();
}
while(ans.equalsIgnoreCase("Yes"));
}
}
Convert the string to lower case characters using the String.toLowerCase() method.
// ...
string1 = input.readLine().toLowerCase();
// ...
pick = input.readLine().toLowerCase();
// ...
The easiest solution is to make 2 new strings like this:
string1_lower = string1.toLowerCase();
pick_lower = pick.toLowerCase();
And use those two variables during comparison.
I understand that the question is old and the OP might have got his answer. But i am putting this out here just in case if anybody needs it in the future.
public static void main(String[] args) {
String s="rEmember";
for(int i = 0; i <= s.length() - 1; i++){
int count = 0;
for(int j = 0; j <= s.length() - 1; j++){
if(Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(j))){
count++;
}
}
System.out.println(s.charAt(i) + " = " + count + " times");
}
}
Related
Input:
2,3,1
5,2,3
Expected Output:
2,5,3,2,1,3
All digits should be separated with a comma.
My code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input1 = scanner.nextLine();
char[] elms1 = input1.toCharArray();
String input2 = scanner.nextLine();
char[] elms2 = input2.toCharArray();
for (int i = 0; i < elms1.length; i++)
System.out.print(elms1[i] + "," + elms2[i]);
}
Alas, it outputs an unexpected result with extra commas and it looks like:
Input:
2,3,1
5,2,3
My Output is:
2,5,,,3,2,,,1,3
How can I eliminate extra commas to get the right output?
What you have to do is to just make a little change in your print statement as:
for (int i = 0; i < elms1.length; i++) {
if (i == elms1.length - 1) {
System.out.print(elms1[i] + "," + elms2[i]);
} else {
System.out.print(elms1[i] + "," + elms2[i] + ",");
}
}
You can do:
Scanner scanner = new Scanner(System.in);
String input1 = scanner.nextLine();
List<Integer> elms1 = Arrays.stream(input1.split(",")).map(Integer::parseInt).collect(Collectors.toList());
String input2 = scanner.nextLine();
List<Integer> elms2 = Arrays.stream(input2.split(",")).map(Integer::parseInt).collect(Collectors.toList());
for (int i = 0; i < elms1.size()-1; i++) {
System.out.print(elms1.get(i) + "," + elms2.get(i) + ",");
}
System.out.print(elms1.get(elms1.size()-1) + "," + elms2.get(elms1.size()-1));
Output (based on your input):
2,5,3,2,1,3
You can change your print statement for your current code which would take 2 characters from each array at a time considering commas to be a valid character input. Here's your code fix:
for (int i = 0; i < elms1.length; i += 2) {
if (i == elms1.length - 1)
System.out.print(elms1[i]+","+elms2[i]);
else
System.out.print(elms1[i]+""+elms1[i+1]+""+elms2[i]+""+elms2[i+1]);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create a program that will display the number of occurrences of a character in a string and also count them. Right now the code just counts the characters.
I want to make the following changes:
1) How do I make this program only count one type of a character, like a or c in a string I love ice cream.
2) How do I also print the character in a string, let's say there are two d my program will then display 2 d first.
3) For the Scanner input = new Scanner(System.in); part I get error in my eclipse, says scanner cannot be resolved to a type.
Also feel free to comment on anything need to be improved in the code. Basically just want a simple program to display all the C in a string and then count the string's occurrence. I want to then mess around the code on my own, change it so I can learn Java.
So this is my code so far:
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < length; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("Number of Occurrence of " +
str.charAt(i) + " is:" + count[str.charAt(i)]);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str);
}
}
Try this
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
// Whatever is the input it take the first character.
char searchKey = input.nextLine().charAt(0);
countString(str, searchKey);
}
public static void countString(String str, char searchKey) {
// The count show both number and size of occurrence of searchKey
String count = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == searchKey)
count += str.charAt(i) + "\n";
}
System.out.println(count + "\nNumber of Occurrence of "
+ searchKey + " is " + count.length() + " in string " + str);
}
You could utilize the fact that each char can be used as an index into an array and use an array to count up each character.
public class Count {
static final int MAX_CHAR = 256;
private static void countString(String str, Character character) {
int [] counts = new int[MAX_CHAR];
char [] chars = str.toCharArray();
for (char ch : chars) {
if (character!=null && character!=ch) {
continue;
}
counts[ch]++;
}
for (int i=0; i<counts.length; i++) {
if (counts[i]>0) {
System.out.println("Character " + (char)i + " appeared " + counts[i] + " times");
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
countString(str, 'e');
}
}
you can take input from user "which character he/she wants to count".
To show the occurrence of character see code below.
You need to import java.util.Scanner class.
Here is your code:
import java.util.Arrays;
import java.util.Scanner;
public class Count {
public static void countString(String str)
{
if(str!=null) {
int length = str.length();
// Create an array of given String size
char ch[] = str.toCharArray();
Arrays.sort(ch);
if(length>0) {
char x = ch[0];
int count = 1;
for(int i=1;i<length; i++) {
if(ch[i] == x) {
count++;
} else {
System.out.println("Number of Occurrence of '" +
ch[i-1] + "' is: " + count);
x= ch[i];
count = 1;
}
}
System.out.println("Number of Occurrence of '" +
ch[length-1] + "' is: " + count);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();//"geeksforgeeks";
countString(str);
}
}
See the snippet below for a way to do it in Java8
public static void main(String[] args) {
// printing all frequencies
getCharacterFrequency("test")
.forEach((key,value) -> System.out.println("Key : " + key + ", value: " + value));
// printing frequency for a specific character
Map<Character, Long> frequencies = getCharacterFrequency("test");
Character character = 't';
System.out.println("Frequency for t: " +
(frequencies.containsKey(character) ? frequencies.get(character): 0));
}
public static final Map<Character, Long> getCharacterFrequency(String string){
if(string == null){
throw new RuntimeException("Null string");
}
return string
.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
You just have to modify this line of code:
using for loop, print str.charAt(i) for count[str.charAt(i) times in your if statement.
if (find == 1) {
for(int k=0;k< count[str.charAt(i)];k++)
System.out.print(str.charAt(i)+",");
System.out.println(count[str.charAt(i)]);
}
Edit: modified based on your comment, if you want the whole code
import java.util.*;
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < length; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j]){
//System.out.println(str.charAt(i));
find++;
}
}
if (find == 1) {
for(int k=0;k< count[str.charAt(i)];k++)
System.out.print(str.charAt(i)+",");
System.out.println(count[str.charAt(i)]);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksfeorgeeks";
str = input.nextLine();
countString(str);
}
}
output
g,g,2
e,e,e,e,e,5
k,k,2
s,s,2
f,1
o,1
r,1
I know you are beginner but if you want to try new version java 8 features which makes our coding life simple and easier you can try this
public class Count {
static final int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str, 'e');
}
public static void countString(String str, char value)
{
List<String> l = Arrays.asList(str.split(""));
// prints count of each character occurence in string
l.stream().forEach(character->System.out.println("Number of Occurrence of " +
character + " is:" + Collections.frequency(l, character)));
if(!(Character.toString(value).isEmpty())) {
// prints count of specified character in string
System.out.println("Number of Occurrence of " +
value + " is:" + Collections.frequency(l, Character.toString(value)));
}
}
And this is the code with requirements mentioned in comments
public class Count {
static final int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str, 'e');
}
public static void countString(String str, char value)
{
String[] arr = str.split("");
StringBuffer tempString = new StringBuffer();
for(String s:arr) {
tempString.append(s);
for(char ch:s.toCharArray()) {
System.out.println("Number of Occurrence of " +
ch + " is:" + tempString.chars().filter(i->i==ch).count());
}
}
if(!(Character.toString(value).isEmpty())) {
StringBuffer tempString2 = new StringBuffer();
for(String s:arr) {
tempString2.append(s);
for(char ch:s.toCharArray()) {
if(ch==value) {
System.out.println("Number of Occurrence of " +
ch + " is:" + tempString2.chars().filter(i->i==ch).count());
}
}
}
}
}
}
You can use this code below;
import java.util.Scanner;
public class Count {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char key = input.nextLine().charAt(0);
countString(str, key);
}
public static void countString(String str, char searchKey) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == searchKey)
count++;
}
System.out.println("Number of Occurrence of "
+ searchKey + " is " + count + " in string " + str);
for (int i = 0; i < count; i++) {
System.out.println(searchKey);
}
if (count > 0) {
System.out.println(count);
}
}
}
I would create a method such as the one below:
public static String stringCounter(String k) {
char[] strings = k.toCharArray();
int numStrings = strings.length;
Map<String, Integer> m = new HashMap<String, Integer>();
int counter = 0;
for(int x = 0; x < numStrings; x++) {
for(int y = 0; y < numStrings; y++) {
if(strings[x] == strings[y]) {
counter++;
}
}m.put(String.valueOf(strings[x]), counter);
counter = 0;
}
for(int x = 0; x < strings.length; x++) {
System.out.println(m.get(String.valueOf(strings[x])) + String.valueOf(strings[x]));
}
return m.toString();
}
}
Obviously as you did, I would pass a String as the argument to the stringCounter method. I would convert the String to a charArray in this scenario and I would also create a map in order to store a String as the key, and store an Integer for the number of times that individual string occurs in the character Array. The variable counter will count how many times that individual String occurs. We can then create a nested for loop. The outer loop will loop through each character in the array and the inner loop will compare it to each character in the array. If there is a match, the counter will increment. When the nested loop is finished, we can add the character to the Map along with the number of times it occurred in the loop. We can then print the results in another for loop my iterating through the map and the char array. We can print the number of times the character occurred as you mentioned doing, along with the value. We can also return the String value of the map which looks cleaner too. But you can simply make this method void if you don't want to return the map. The output should be as follows:
I tested the method in the main method by entering the String "Hello world":
System.out.println(stringCounter("Hello World"));
And here is our final output:
1H
1e
3l
3l
2o
1
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}
You get the number of times each character occurs in the String and you can use either the Map or print the output.
Now for your scanner. To add the Scanner to the program here is the code that you will need to add at the top of your code to prompt the user for String input:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a String: ");
String str = scan.nextLine();
System.out.println(stringCounter(str));
You have to create the Scanner Object first, adding System.in to the constructor to get input from the keyboard. You can then prompt the user with a print statement to enter a String. You can then create a String variable which will store the String by calling the "Scanner.nextLine()" method as the value. This will grab the next line of userinput from the keyboard. Now you can pass the userinput to our method and it will operate the same way. Here is what it should look like to the user:
Please enter a String:
Hello World
1H
1e
3l
3l
2o
1
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}
So my task was to create a program that takes a file as input and counts the occurrences of each alphabetic character in it. Then I shall print the letter, the amount of times it occurs and the frequency of it.
And I get it to work almost as planned. The only problem I have is that when I print, it also prints the number of dots(.) in the file. And I can't stop it from doing that. Help please..
public class CountOccurences {
private static Scanner input;
public static void main(String [] args) throws FileNotFoundException {
DecimalFormat dec = new DecimalFormat("#.000");
input = new Scanner(new File("story.txt"));
int[] ltrCtr = new int[127]; // This array counts the number of occurences for every letter / symbol on the ascii table.
String str = "";
// Puts the textfile as a String
while(input.hasNext()) {
str += input.next();
}
char[] text = str.toCharArray();
char temp; int tempInt;
int ctr = 0;
for(int i = 0; i < text.length; i++) { // Loops through the text
temp = text[i]; // Gets the char at i
tempInt = (int)temp; // Get the ascii value of the char at i
ltrCtr[tempInt]++;
if(Character.isAlphabetic(text[i])) {
ctr++;
}
}
System.out.println("Letter" + " Amount" + " Freq");
for(int i = 0; i < ltrCtr.length; i++) {
if(ltrCtr[i] >= 1 && (int)ltrCtr[i] != 46) {
System.out.println(" " + (char)i + " " +
ltrCtr[i] + " " +
dec.format((double)ltrCtr[i]/ctr) + "%");
}
}
input.close();
}
}
I believe you meant to use isLetter, not isAlphabetic.
Mureinik is right, isLetter solves your problem. Here's a post explaining the differences between isLetter and isAlphabetic to make it clearer: What is the difference between Character.isAlphabetic and Character.isLetter in Java?
I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}
So I'm trying to find all the uppercase letters in a string put in by the user but I keep getting this runtime error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4
at java.lang.String.charAt(String.java:686)
at P43.main(P43.java:13)
I feel foolish but I just can't figure this out and oracle even talks about charAt on the page about java.lang.StringIndexOutOfBoundsException
Here is my code for finding the uppercase letters and printing them:
import java.io.*;
import java.util.*;
public class P43{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//Uppercase
String isUp = "";
System.out.print("Please give a string: ");
String x = in.next();
int z = x.length();
for(int y = 0; y <= z; y++){
if(Character.isUpperCase(x.charAt(y))){
char w = x.charAt(y);
isUp = isUp + w + " ";
}
}
System.out.println("The uppercase characters are " + isUp);
//Uppercase
}
}
I'd really appreciate any input and or help.
for(int y = 0; y <= z; y++){
should be
for(int y = 0; y < z; y++){
Remember array index starts from ZERO.
String length returns
the number of 16-bit Unicode characters in the string
Because loop started from ZERO, loop should terminate at length-1.
The array index out of bounds is due to the for loop not terminating on length - 1, it is terminating on length
Most iterating for loops should be in the form:
for (int i = 0; i < array.length; i++) {
// access array[i];
}
It's the same with a string.
Perhaps a cleaner way would be:
String inputString; // get user input
String outputString = "";
for (int i = 0; i < inputString.length; i++) {
c = inputString.charAt(i);
outputString += Character.isUpperCase(c) ? c + " " : "";
}
System.out.println(outputString);
Edit: Forgot String Doesn't implement Iterable<Character>, silly Java.
With Java 8 you can also use lambdas. Convert the String into a IntStream, use a filter to get the uppercase characters only and create a new String by appending the filtered characters to a StringBuilder:
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
//Uppercase
String isUp = in.next()
.chars()
.filter(Character::isUpperCase)
.collect(StringBuilder::new, // supplier
StringBuilder::appendCodePoint, // accumulator
StringBuilder::append) // combiner
.toString();
System.out.println("The uppercase characters are " + isUp);
//Uppercase
Inspired by:
Adam Bien - Streaming A String
Simplest way to print anIntStream as a String
Try this...
Method:
public int findUpperChar(String valitateStr) {
for (int i = valitateStr.length() - 1; i >= 0; i--) {
if (Character.isUpperCase(valitateStr.charAt(i))) {
return i;
}
}
return -1;
}
Usage:
String passwordStr = password.getText().toString();
.......
int len = findUpperChar(passwordStr);
if ( len != -1) {
capitals exist.
} else {
no capitals exist.
}
Hi one of the easy step to find uppercase char in a given string...
Program
import java.io.*;
public class testUpper
{
public static void main(String args[]) throws IOException
{
String data,answer="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any String : ");
data=br.readLine();
char[] findupper=data.toCharArray();
for(int i=0;i<findupper.length;i++)
{
if(findupper[i]>=65&&findupper[i]<=91) //ascii value in between 65 and 91 is A to Z
{
answer+=findupper[i]; //adding only uppercase
}
}
System.out.println("Answer : "+answer);
}
}
Output
Enter any String :
Welcome to THe String WoRlD
Answer : WTHSWRD
You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, I suggest importing the least number of libraries into your class. Please avoid using .* while importing.
import java.util.Scanner;
public class P43 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
String x = in.next();
x.chars().filter(c -> Character.isUpperCase(c))
.forEach(c -> System.out.print((char) c + " "));
}
}
Sample input:
saveChangesInTheEditor
Sample output:
C I T E
import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
StringBuilder s=new StringBuilder();
Scanner input = new Scanner(System.in);
System.out.println("Enter your String");
String str= input.nextLine();
for(int i=0; i<str.length(); i++)
{
if(Character.isUpperCase(str.charAt(i)))
{
System.out.print(str.charAt(i)+" ");
}
}
}
}
The simplest way I know is to use regex replacement.
isUp = x.replaceAll("[^A-Z]", "");
In simple terms, this uses a regular expression which matches any character which is not in the A-Z range, and replaces it with an empty string.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
String str= input.nextLine();
int ascii;
for(int i=0; i<str.length(); i++) {
ascii = str.charAt(i);
System.out.println(ascii);
if (ascii >= 65 && ascii <= 90) {
System.out.println("captal letter found ::: "+ascii);
}
}
}
public class Cama {
public static void main(String[] args) {
String camal = "getStudentByName";
String temp = "";
for (int i = 0; i < camal.length(); i++) {
if (Character.isUpperCase(camal.charAt(i))) {
System.out.print(" " + Character.toLowerCase(camal.charAt(i)));
} else if (i == 0) {
System.out.print(Character.toUpperCase(camal.charAt(i)));
}else{
System.out.print(camal.charAt(i));
}
}
}
}