This question already has answers here:
Simple way to count character occurrences in a string [duplicate]
(15 answers)
Closed 4 years ago.
String sentence = JOptionPane.showInputDialog (null, "Write a sentence.");
String letter = JOptionPane.showInputDialog(null, "Write a letter");
while (true) {
if (letter.equals("Stop"))
System.exit(0);
//to calculate number of specific character
else {
int countLetter = 0;
int L = letter.length();
for (int i = 0; i < L; i++) {
if ((letter.charAt(i) = .....))
countLetter++;
}
}
}
Is it possible to replace the dots to make the program count how many times the given letter occures in the sentence written in the first string?
Since Java 8, there is an elegant solution to this.
int count = letter.chars().filter(ch -> ch == 'e').count();
This will return the number of occurences of letter 'e'.
if your String letter contains a one character use this letter.charAt(0) and then replace dots with this. Also remember to use == instead of = here. = means you are just asigning and == uses to compare two values.
If you have to use a for loop and want to stick to the old fashioned way, try this:
String sentence = "This is a really basic sentence, just for example purpose.";
char letter = 'a';
int occurrenceOfChar = 0;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == letter) {
occurrenceOfChar++;
}
}
System.out.println("The letter '" + letter
+ "' occurs " + occurrenceOfChar
+ " times in the sentence \""
+ sentence + "\"");
The sentence and the letter are just examples, you have to read the user input.
You can use Guava Lib to perform this operation faster without iterating string.
CharMatcher.is('e').countIn("Write a letter");
Will return 3
Related
I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```
I'm trying to create program that will ask the user to enter serial numbers in a specific format and the program will verify if the codes are valid or not.
The format should be 2 numbers, followed by a dash, 4 numbers, a dot, then 4 numbers and 2 letters (note: letters accepted are only a,b,c).
Example of valid format:
31-0001.2341ac
00-9999.0001cb
If the length of the string is longer/shorter than the format (14 characters total length) it should display invalid. Same thing, if other characters were used it will also say invalid.
This is the code that I have done so far. Im not sure how I can achieve the exact specified format. Hopefully someone can help..
import java.util.Scanner;
public class SerialCheck{
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("How many serial numbers would you like to check: ");
int length = sc.nextInt();
int valid = 0;
String[] sSerials = new String[length];
for (int nCtr = 0; nCtr < length; nCtr++){
System.out.print ("Enter Serial " + (nCtr+1) + ": ");
sSerials[nCtr] = sc.next();
}
System.out.println();
System.out.println("The following were added: ");
for(int nCtr = 0; nCtr < length; nCtr++){
System.out.println(sSerials[nCtr]);
}
System.out.println();
for(int nCtr = 0; nCtr < length; nCtr++){
for (int x = 0; x < sSerials[nCtr].length(); x++){
char c = sSerials[nCtr].charAt(x);
if((sSerials[nCtr].charAt(x)!='a') ||
(sSerials[nCtr].charAt(x)!='b') ||
(sSerials[nCtr].charAt(x)!='c') ||
(sSerials[nCtr].charAt(x)!='-') ||
(sSerials[nCtr].charAt(x)!='.')){
valid--;
}
else{
valid++;
}
}
if (valid < 0 && sSerials[nCtr].length() != 14){
System.out.println("The address is invalid.");
}
else{
System.out.println("The address is valid.");
}
}
}
}
I frequently post answers saying "don't use regular expressions". But in this case: use regular expressions. They are the right tool for this job.
boolean isValid = sSerials[nCtr].matches(
"[0-9]{2}" // Match 2 digits
+ "-" // Then a dash
+ "[0-9]{4}" // Then 4 digits
+ "\\." // Then a dot (which must be escaped)
+ "[0-9]{4}" // Then 4 digits
+ "[abc]{2}" // Then 2 a, b or c.
This regex is split up simply to explain the parts of it. You can write the string literal on one line:
boolean isValid =
sSerials[nCtr].matches("[0-9]{2}-[0-9]{4}\\.[0-9]{4}[abc]{2}");
You can use some websites or utility like regexr.com which helps building you regular expression for required string(Seqial number for your product).
Then use java.util.regex package for identifying them,
The linkjava.util.regex given will expose you all the functions using which you can filter perticular type of string.
I am taking an intro class to Java and we have a project that deals with a hangman game. I have most of the code worked out but there is a bug that I can't seem to resolve.
First, the program prompts the user for a letter and one space where they think the letter goes, then the program displays a word in a series of hyphens and, if the user makes a correct guess, the letter in the corresponding hyphen is replaced with said letter.
For testing purposes, the word has been defaulted to narrow.
So if I were to guess the letter r and for space, I were to guess index 2, the program would give me:
Guess a letter: r
Guess a space: 2
Guess: --r---
The problem I am having is that when I guess the index 3 for space and try to guess the next r, the program just gives me the same output as before.
We are not allowed to use arrays or string builder because we have not talked about them yet.
Here are my variables:
// default word for testing
String blank = "narrow";
// variables to manipulate the string
String start = "";
String end = "";
String word = "";
// variables for input and output
// input is used for the user's letter guess
String input;
// space is used for the user's index guess
String space = "";
// guess is used at the end to display the word to the user and set equal to word after
// it has been manipulated
String guess = "";
Here is the code where the string is being manipulated.
for (int i = 0; i < blank.length(); i++) {
if (i == blank.indexOf(input)) {
start = guess.substring(0, i);
end = guess.substring(i + 1);
word = start.concat(input).concat(end);
}
}
I think it has to do with the if statement, but I have tried some other things and they have not worked. Any help would be appreciated.
Thank you.
The problem with your code is that everytime the blank.indexOf(input) returns 2 everytime (indexOf returns the first occurance of 'r' which is 2)
You can change the condition to check if the character at the space that the user guessed is the contains the letter that the user guessed.
You can do this as follows:
Maintain the pattern to be printed. Make a variable for this.
update the pattern everytime the user guesses correctly.
Note: In the below code guess is the variable I am talking about which is initially set to "------" for the word "narrow"
// check if the space has the letter you guessed
if (blank.charAt(space) == input.charAt(0)) {
// if it has just update the pattern string to also contain the new letter
guess = guess.substring(0, space) + input + guess.substring (space + 1)
You can just print or return (if it is a method) the pattern string.
I think blank.indexOf(input) returns only the first occurrence index of that input character. So you need to use this indexOf(int ch, int fromIndex).
In your case, store index of last occurrence of the input char in some int variable, then use that as fromIndex.
int lastOccurrence = 0;
for (int i = 0; i < blank.length(); i++) {
if (i == blank.indexOf(input, lastOccurrence)) {
lastOccurrence = i;
start = guess.substring(0, i);
end = guess.substring(i + 1);
word = start.concat(input).concat(end);
}
}
I would write it like this:
//set up variables
Scanner keyboard = new Scanner(System.in);
String word = "narrow";
String display = "";
for (int i = 0; i < word.length(); i++) {
display = display + "-";
}
//loop until the word is guessed
while (display.contains("-")) {
//show the user flow, take input
System.out.println("Guess: " + display);
System.out.print("Guess a letter: ");
String letter = keyboard.nextLine();
System.out.print("Guess a space: ");
String spaceStr = keyboard.nextLine();
int space = Integer.parseInt(spaceStr);
//check if the guess is right
if (letter.equals(word.charAt(space) + "")) {
//modify the string shown to the user
String temp = display.substring(space + 1);
display = display.substring(0, space);
display = display + letter + temp;
}
}
The key is to have one variable that is shown to the user and one which holds the real word. When they make a correct guess, you can modify the string which is shown to the user.
indexOf(String str) returns the index within this string of the FIRST OCCURENCE of the specified substring. More of this here
Best way I would suggest to do, is to change the output ONLY if the user got it right. Hence, for every guess I would do:
if(blank.charAt(space) == input.charAt(0))
{
start = guess.substring(0, space);
end = guess.substring(space + 1);
word = start.concat(input).concat(end);
}
This question already has answers here:
How to print each character from a string?
(3 answers)
Closed 7 years ago.
I am having trouble printing a string one character at a time in java. I have to input a string and output it one letter per line. My code is as follows
import java.util.*;
public class StringToMultiLines
{
public static void main(String[] args)
{
String myString;
int placeInString = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a string.");
myString = scan.nextLine();
while(placeInString <= myString.length())
{
System.out.println("" + myString.substring(placeInString));
placeInString ++;
}
}
}
This ouptuts the following'
Please enter a string.
Hello
Hello
ello
llo
lo
o
I have also tried this with no luck
System.out.println("" + myString.subsstring(0, placeInString));
and
System.out.println("" + myString.subsstring(placeInString, placeInString));
You could simply use a for-loop and String#charAt (or String#toCharArray)
for (int index = 0; index < myString.length(); index++) {
System.out.println(myString.charAt(index));
}
or
for (char c : myString.toCharArray()) {
System.out.println(c);
}
Have a look at The for statement and the String JavaDocs for more details
You're looking for charAt:
System.out.println(myString.charAt(placeInString));
And remember that indices start from 0, so myString.length() is an invalid index. Thus you need
while (placeInString < myString.length())
instead of
while (placeInString <= myString.length())
Well, I have two strings to compare and check letter by letter if they match, and if hits a '-' i need to count how many '-' there's in sequence and put them in a group as if they were only one char and count how many T and C there in this group of '-'. The output should be like 2.1T and 2.2C and the other one 5.2C.
String dna1 = "TC---CA--";
String dna2 = "TCTCCCACC";
char[] dnaChar = dna1.toCharArray(), dna2Char = dna2.toCharArray();
int cont = 0;
int letters = 0;
for (int i = 0; i < dnaChar.length; i++) {
if (dnaChar[i] != dna2Char[i]) {
int mut = i + 1;
if (dna1.charAt(i) == '-') {
cont++;
mut -= cont;
if (dna2.charAt(i) == 'C') {
letters++;
}
System.out.println(mut + "." + letters + dna2.charAt(i));
} else {
letters = 0;
cont = 0;
mut += 1;
System.out.println("" + dna1.charAt(i) + " " + mut + " " + dna2.charAt(i));
}
}
}
The output
2.0T
2.1C
2.2C
4.3C
4.4C
And what i want 2.1T 2.2C 5.2C
The output that you expect will never be obtained from your above code.. Because in your if construct will be executed every time you encounter a '-' in your first string.. And hence you will have 5 outputs, not 3..
Second, to get what you need, you will have to do some extra work here..
First When you encounter a '-' in your 1st String, you need to store the corresponding character from your second String into some variable.. Because you need it to check for continuous characters.
Second, each time to get a '-', check the current character with the last character matched for the previous '-'. If it is the same, increase the count by 1,
If it is not the same, just print what you want.. and reset your count to 0
As soon as you encounter the character which not '-' in your first string, print the current character and the count value, and reset them..
You can try to code according to the steps I have mentioned..
*PS: - For any problem you get to code, you should first write down the steps you should follow to solve it on paper. Then convert it to code step-by-step. It will be easier to understand the problem and solve it also..