I am trying to have my code output the exact number of times a certain character is said in an inputted sentence (For example e).
I tried using a char and for statement so its able to count but it gives me the wrong value
int countChar;
char e = '\0';
String str;
int count = 0;
System.out.println("input your sentence:");
str = in.next();
for(i=0; i < str.length(); i++)
{ if(str.charAt(i) == e)
count++;
}
System.out.println(count);
You need to change if(str.charAt(i) == e) to if(str.charAt(i).equals("e")), you don't really require a variable for this. You just require the quotation marks, and since you are comparing a string, you should use the above String.equals() method.
If you are looking for uppercase letters as well, use the || (OR) operator and do the same but replace the lowercase e with an uppercase
You should use 'e' instead of '\0' when comparing the characters
Related
I am trying to create a program that loops through a string, and if it is a vowel that adds it to a variable and then displays. The idea is not to use regular expressions so I use a for. And the problem is that it does not show me the result well, can you help me?
import java.util.Scanner;
import java.lang.StringBuilder;
public class ReemplazarVocales {
public static void main(String[] args) {
Scanner InputText = new Scanner(System.in);
StringBuilder str = new StringBuilder();
System.out.println("Escribe una frase\n");
String Sentence = InputText.next();
Sentence = Sentence.toLowerCase();
char Vocal;
for (int i=0;i <= Sentence.length();i++){
Vocal = Sentence.charAt(i);
String Consonant = Character.toString(Vocal);
if (Consonant != "a" ||Consonant !="e" || Consonant !="i" || Consonant !="o" || Consonant!="u"){
str.append(Consonant);
}
}
System.out.println("\nTu frase sin vocales " + str);
}
}
There seem to be three problem in you code:
you are looping from index int i=0 till i=length, which will give you IndexOutOfBound.
Since string indexing start from 0 you can loop like
for (int i=0;i < Sentence.length();i++){
Vocal = Sentence.charAt(i);
String VocalP = Character.toString(Vocal);
if (!VocalP.equals("a") && !VocalP.equals("e") && !VocalP.equals("i") && !VocalP.equals("o") && !VocalP.equals("u")){
str.append(VocalP);
}
}
you need to have (&&) instead of Logical (||) because you wish to eliminate all the vowels.
It is adviceable to do string comparision using equals or equalsIgnoreCase to compare two strings
I am trying to create a program that loops through a string, and if it
is a vowel that adds it to a variable and then displays.
You are trying to get a character at the index = Sentence.length() which is not possible because java stores the characters in a string starting with index, 0 and therefore the last index is equal to the length-of-the-string minus one. Trying to access an index beyond the limits results in StringIndexOutOfBoundsException.
You do not need to convert a char into a String in order to add it to a StringBuilder; you can append a char value directly to the StringBuilder object.
You need to use == instead of !=.
You need to use Scanner#nextLine instead of Scanner#next which stops scanning the input as soon as it encounters whitespace.
A. Replace
String Sentence = InputText.next();
with
String Sentence = InputText.nextLine();
B. Replace
for (int i=0;i <= Sentence.length();i++)
with
for (int i = 0; i < Sentence.length(); i++)
C. Replace
Vocal = Sentence.charAt(i);
String Consonant = Character.toString(Vocal);
if (Consonant != "a" ||Consonant !="e" || Consonant !="i" || Consonant !="o" || Consonant!="u"){
str.append(Consonant);
}
with
Vocal = Sentence.charAt(i);
// String Consonant = Character.toString(Vocal);// It's not needed
if (Vocal == 'a' || Vocal == 'e' || Vocal == 'i' || Vocal == 'o' || Vocal == 'u') {
str.append(Vocal);
}
I also recommend you follow the Java naming conventions e.g. Vocal should be vocal and Sentence should be sentence as per the naming conventions.
You wrote:
if (VocalP!="a" || VocalP!="e" || VocalP!="i" || VocalP!="o" || VocalP!="u")
which if you look closely will always be true.
for example if you take the first two options only:
if (VocalP!="a" || VocalP!="e")
if the letter is not 'a' OR the letter is not 'b'
and the letter is 'a' it will still evaluate to true because it is not 'e'
from your question you should be using == instead of !=
so try:
if (VocalP=="a" || VocalP=="e" || VocalP=="i" || VocalP=="o" || VocalP=="u")
import java.util.Scanner;
import java.util.Stack;
public class Stack_1 {
public static void main(String[] args) {
String val;
Scanner input = new Scanner(System.in);
System.out.println("Enter Text: ");
val = input.nextLine();
push(val);
}
public static void push(String str) {
Stack<Character> stk = new Stack<Character>();
for (int i = 0; i < str.length(); i++) {
stk.push(str.charAt(i));
}
System.out.println(stk);
String reverseString = "";
String original = "";
int length = original.length();
for (int i = length - 1; i >= 0; i--)
reverseString = reverseString + original.toUpperCase().charAt(i);
if (original.toUpperCase().equals(stk))
System.out.println("The string is a palindrome.");
else if (reverseString.toUpperCase().equals(stk))
System.out.println("The string is not a palindrome.");
}
}
Can anyone help me out. I didn't know where I went wrong. The question was to create a stack (Character), and display the text where it is a palindrome or not. The user had to enter input.
P.S This was one of my lab test.
If I followed the code correctly, the problem appears to be that the OP is comparing a String object (either original or reverseString) to Stack<Character> object.
So, the probable failure is the incorrect attempted comparison of a String object to a Stack object.
I think there is a 2nd failure in the if/else if logic given that an example input of "cool" is not a palindrome, but no output is produced in such a case.
EDIT: while the OP code does attempt to adjust for the case of the entered data (not given in the question as to whether that is a requirement or not), it does not account for spaces or other punctuation. According to the entry on Wikipedia about Palindromes, punctuation is also usually ignored. Again, whether being concerned about spaces, periods, dashes, etc. was part of the exercise is not defined in the question. The question is a bit under specified in terms of full requirements.
I would think a solution using a stack would take a String, push it by character to a Stack (probably correcting for case and stripping out all punctuation at that time), and then do a comparison by popping from the Stack. I think the OP code is missing part of the requirement in using a Stack.
Example code to have only characters on the Stack. There are other approaches, of course:
// push by character onto the stack; use only
// characters, and convert to lower case
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if ( (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ) {
stk.push(Character.toLowerCase(c));
}
}
Example to remove all non characters from a check String:
// convert out comparison String to lower case and remove
// all non letters
String chk = str.toLowerCase().replaceAll("[^a-z]", "");
Example loop to use the Stack to check against the String:
// assume we have a palindrome
boolean palindrome = true;
// counter across the String
int i = 0;
// loop while there is more on the stack and we haven't
// failed our test
while (! stk.isEmpty() && palindrome) {
Character c = stk.pop();
palindrome = (c == chk.charAt(i++));
}
Sample Test Data:
cool is a palindrome: false
mom is a palindrome: true
Never odd or even is a palindrome: true
A man, a plan, a canal - Panama! is a palindrome: true
Here i have code to check whether given string is palindrome or not but don't know the procedure to reduce characters from last.To make change the character i need to follow the rule as: Eg String input="abcde".Letter 'e' can be converted to 'd' but not 'e' to 'd' if character becomes 'a' we can't change further.Here is my code:
public static void main(String[] args) {
String input = "abcd";
String temp = input;
String output = "";
for (int i = output.length() - 1; i >= 0; i--) {
output = output + output.charAt(i);
}
if(temp.equals(output)){
System.out.println("String is palindrome");
}else{
System.out.println("Not a palindrome");
}
}
output order logic is as follows:
if input is =abcd
abcc('d' converted to 'c')and check for palindrome
abcb('c' converted to 'b')and check for palindrome
abca('b' converted to 'a')and check for palindrome
abba('a' further we can't change so shift to previous letter 'c' and change to 'b')
and check for palindrome
String is palindrome and count is=4
if input=cbdf
cbde('f' converted to 'f')and check for palindrome
cdbd('e' converted to 'd')and check for palindrome
cdbc('d' converted to 'c')and check for palindrome
cdbb('c' converted to 'b')and check for palindrome
cdba('b' converted to 'a')and check for palindrome
cdaa('a' further we can't change so shift to previous letter 'b' and change to 'a')
and check for palindrome
ccaa('a' further we can't change so shift to previous letter 'd' and change to 'c')
and check for palindrome
cbaa('c' converted to 'b')and check for palindrome
caaa('a' further we can't change so shift to previous letter 'c' and change to 'b')
and check for palindrome
baaa('b' converted to 'a')and check for palindrome
aaaa now string is palindrome
String is palindrome and count is=10
finally i need the count to make string palindrome.
Assuming that I understand your problem, you are going about this in an inefficent way. Here is how I would do this:
String toPalindrome(String str){
StringBuilder reverse = new StringBuilder(str).reverse();
for(int idx = 0; idx < str.size()/2; idx++)
if(str.getCharAt(idx) < reverse.getCharAt(idx))
reverse.setCharAt(idx, str.getCharAt(idx));
return reverse.subString(0,str.size()/2) + reverse.reverse().subString(str.size()/2);
}
Aside from the off-by-one errors in this code, this should work to produce the output you need.
Using this approach, we don't have to decrement each character one by one - we rather just immediately replace each character with the target value. We also never have to check if it is a palindrome, since this method is guaranteed to produce one (after all, it is concatenating a string with its mirror image in the return step).
EDIT: seeing that we need only return the number of times characters were decremented, we can do something even simpler:
int abs(int x){
return x>0?x:-x;
}
int palindromeCounts(String str){
int count = 0;
for(int idx = 0; idx < str.length()/2; idx++)
count += abs(str.charAt(idx) - reverse.charAt(str.length()-1-idx));
return count;
}
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..
I need to count the number of words and I am assuming the correct way to do it is by calculating the number of times that the previous character in a string is not a letter (ie other characters) because this is to assume that there would be colons,spaces,tabs, and other signs in the string.
So at first my idea was to loop through each character and count how many times that you will not get a letter of an alphabet
for(int i = 0; i < string.length(); i++) {
for(int j = 0; i < alphabets.length(); j++) {
if (string.charAt(i-1) == alphabets.charAt(j)) {
counter++;
}
}
}
However I will always get an array out of bounds because of this. So, I kinda need a little help or another way that can actually be more efficient.
I thought of using Matches to only [a-zA-z] but I'm not sure how do I handle a char to be comparable to a string in counting how many times it occurs.
Thank you
You can use String.split() to convert the string into an array, with one word in each element. The number of words is given by the length of the array:
int words = myString.split("\s+").length;
Your suggestion to use a regex like "[A-Za-z]" would work fine. In a split command, you'd split on the inverse, like:
String[] words = "Example test: one, two, three".split("[^A-Za-z]+");
EDIT: If you're just looking for raw speed, this'll do the job more quickly.
public static int countWords(String str) {
char[] sentence = str.toCharArray();
boolean inWord = false;
int wordCt = 0;
for (char c : sentence) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
if (!inWord) {
wordCt++;
inWord = true;
}
} else {
inWord = false;
}
}
return wordCt;
}
This problem is slightly more complicated than your algorithm allows.
What if there are two or more spaces in a row?
What if the string starts or ends with whitespace (or non-word characters)?
This looks like homework, so I don't want to provide any code. I suggest an alternative approach which is simpler to think about.
Walk through the characters in the string, one by one.
Do something to remember if you are currently scanning a word or if you are not currently scanning a word.
Do something to determine when you enter or leave a word, and increment your counter accordingly.
The reason you are getting an IndexOutOfBoundsException is probably because when i is 0 your inner loop will have string.charAt(i-1) which will throw an exception since 0-1 is -1. If you fix that your method might work, although you can use more efficient techniques.
Addressing the code directly, your first loop has i=0 as the first value of i, but then you ask for
string.charAt(i-1) = string.charAt(-1),
which is where your array-out-of-bounds is coming from.
The second loop has another problem:
for(int j = 0; i < alphabets.length(); j++) {
You may also want to consider apostrophes as parts of words as well.
Use just like this
String s = "I am Juyel Rana, from Bangladesh";
int count = s.split(" ").length;
if (string.charAt(i-1) == alphabets.charAt(j)) {
counter++;
}
You are incrementing the counter if the character is some alphabet character. You should increment it if it is no alphabet character.
The following program will count the number of words in a sentence. In this program, we are counting alphabets just after space. The alphabet can be of lower case or upper case. We are inserting a space at the beginning since people don't start a sentence with space. We also need to take care that any special character or number should not be counted as a word.
`import java.util.Scanner;
public class WordSent {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.println("Enter the sentence");
String str=in.nextLine();
String space=" ";
String spaceword=space.concat(str);
int count=0;
for(int i=0; i<spaceword.length()-1;i++)
{
for (int k=0; k<=25; k++)
{
if(spaceword.charAt(i)==' '&& (spaceword.charAt(i+1)==((char)(65+k)) || spaceword.charAt(i+1)==((char)(97+k))))
{
count++;
}
}
}
System.out.println("Total number of words in a sentence are" +" : "+ count);
}
}`