String wrd;
do
{
wrd = JOptionPane.showInputDialog("Enter a word");
if (!wrd.equalsIgnoreCase("last"))
{
if (wrd.contains("s") || wrd.contains("S"))
{
System.out.println(wrd + " does contain 's' or 'S'");
}
else
{
System.out.println(wrd + " doesn't contain 's' or 'S'");
}
}
}
while (!wrd.equalsIgnoreCase("last"));
System.out.println("Program Ended");
This program basically allows a user to enter any word in until he/she types the word "last".
If the word contains the letter 's' it should display the word + does contain 's' or 'S' else it should display word + doesn't contain 's' or 'S'.
Example: Words entered by user=
• John
• James
• Pie
• Sally
Result:
John does not contain 's' or 'S'
James does contain 's' or 'S'
Pie does not contain 's' or 'S'
Sally not contain 's' or 'S'
The program works but I need to change the if statement so that it recognises lower and uppercase 's' using the equalsIgnoreCase method instead of using
wrd.contains("s") || wrd.contains("S")
Just Try this
String wrd;
do {
wrd = JOptionPane.showInputDialog("Enter a word s");
if (wrd.toLowerCase().contains("s")) {
System.out.println(wrd + " does contain 's' or 'S'");
} else {
System.out.println(wrd + " doesn't contain 's' or 'S'");
}
} while (!wrd.equalsIgnoreCase("last"));
System.out.println("Program Ended");
Related
I am creating a C++ program to validate book name using a function in c++. The function must return 1 if the input is valid and 0 if the input is invalid. Book name can only contain upper case, lower case characters, color(:), comma(,) and space (there should be no consecutive spaces, commas, and colons). And the maximum characters in a character array is 60.
I tried the following way but I am not getting the desired answer.
const int MAX_BOOK_NAME = 60;
bool isValidBookName(char bookName[MAX_BOOK_NAME])
{
int length = strlen(bookName);
if (length > 59)
{
return false;
}
for (int i = 0; i < 59; i++)
{
if (bookName[i] < 'A' || bookName[i] > 'Z' || bookName[i] < 'a' || bookName[i] > 'z' || bookName[i] != ' ' || bookName[i] != ':' || bookName[i] != ',')
{
return false;
}
}
return true;
}
int main()
{
char arr[60];
cout << "Please Enter Your Book Id : ";
cin.getline(arr, 60);
cout << "Your Entered Name is " << isValidBookName(arr) << endl;
}
bookName[i] < 'A' || bookName[i] > 'Z' || bookName[i] < 'a' || bookName[i] > 'z'
These checks match every character because for example (assuming ASCII or compatible encoding) all capital letters match the condition bookName[i] < 'a' and all smaller case letters match bookName[i] > 'Z'. Since these checks are used to match an invalid character, the check is wrong.
std::isalpha can simplify your program greatly, as pointed out in comments.
The logic of your character check is flawed.
The requirement in your question is that each character must be a letter, or a comma, or a colon, or ... etc. The reverse of that is not "not a letter or not a comma or not a colon or ... etc." The reverse is "not a letter and not a comma and not a colon and ... etc."
Im writing a program for class and so far i have the word counter working fine and the vowel part working fine but Consonants and non alpha digits return wrong answers by 1(in certain cases). i think the problem lies in the testing of the characters them selves but i cant seem to find a way around it.
using namespace std;
int main()
{
char ch;
int count = 0;
int vowel = 0;
int cons = 0;
int noalph = 0;
bool inword = 1;
bool space = 0;
while (cin.get(ch)) {
if (ch != ' ') {
inword = 1;
}
if (isspace(ch)) {
space = 1;
}
else if (space && inword) {
count++;
space = 0;
inword = 0;
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' ||
ch == 'y' || ch == 'Y') {
vowel++;
}
if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u' &&
ch != 'A' && ch != 'E' && ch != 'I' && ch != 'O' && ch != 'U' &&
ch != 'y' && ch != 'Y'
&& isalpha(ch)) {
cons++;
}
if (ispunct(ch) || isdigit(ch)) {
noalph++;
}
}
}
if (count > 0) {
count++;
}
//--------------------------------------------
cout << "Total Number of Words = " << count << endl;
cout << "Number of Words Beginning with a Vowel = " << vowel << endl;
cout << "Number of Words Beginning with a Consonant = " << cons << endl;
cout << "Number of Words Beginning with a Non-Alpha = " << noalph << endl;
return 0;
}
Example 1(
Input:--------------------------------------------------------------------
supercalifragilisticexpialidocious
A nonsense-word used esp. by children, now chiefly expressing excited
approbation: fantastic, fabulous.
Made popular by the Walt Disney film "Mary Poppins" in 1964. The
song containing the word was the subject of a copyright infringement
suit brought in 1965 against the makers of the film by Life Music
Co. and two song-writers: cf. quots. 1949, 1951. In view of earlier
oral uses of the word sworn to in affidavits and dissimilarity between
the songs the judge ruled against the plaintiffs.
Taken from the OED.
Output:--------------------------------------------------------------------
Total Number of Words = 86
Number of Words Beginning with a Vowel = 25
Number of Words Beginning with a Consonant = 55
Number of Words Beginning with a Non-Alpha = 5
Expected:------------------------------------------------------------------
Total Number of Words = 86
Number of Words Beginning with a Vowel = 25
Number of Words Beginning with a Consonant = 56
Number of Words Beginning with a Non-Alpha = 5
)
Example 2(
Input:--------------------------------------------------------------------
1996
bottle
12345
radar
a Toyota
Madam, I'm Adam
Was it a rat I saw?
Norma is as selfless as I am, Ron.
A man, a plan, a canal--Panama!
Tarzan raised Desi Arnaz' rat.
Hannah
Lewd did I live, & evil I did dwel.
Excerpts from "The Zen of Programming"
Mary said, "I like the STL."
Output:--------------------------------------------------------------------
Total Number of Words = 56
Number of Words Beginning with a Vowel = 20
Number of Words Beginning with a Consonant = 31
Number of Words Beginning with a Non-Alpha = 4
Expected:------------------------------------------------------------------
Total Number of Words = 56
Number of Words Beginning with a Vowel = 20
Number of Words Beginning with a Consonant = 31
Number of Words Beginning with a Non-Alpha = 5
)
As you can see it breaks at different points, maybe its something simple maybe it not, i would just like some help understanding what is going on, Thank You!
OK, you didn't followed advices in comments, so let do it explicitly.
You are skipping the first word.
Cause of the initialization in this line:
bool space = 0;
you should initialize it as true
bool space = true;
(yes, use true and false for boolean).
you should see that cause you added this lines
if (count > 0) {
count++;
}
to cover this problem. So, remove them.
You also skipped the #include <iostream> directive.
I need to encrypt a simple text file by incrementing each character by 1 i.e 'a' becomes 'b', 'b' becomes 'c' etc. with 'z' becoming 'a'.
I have done this as per the code below, and although majority of my output is correct, it seems to have trouble at the end of each file.
For example, when the input file contains 'a b c d' the output generated is 'b c d ef' as opposed to the answer which should be 'b c d e'. I cannot seem to figure this out.
This is my code for the encrypt function:
void encrypt(char* inFileName, char* outFileName) {
out_stream.open(outFileName);
in_stream.open(inFileName);
if(in_stream.fail()) {
cout << "Failed to open input file." << endl;
exit(1);
}
else {
while(!in_stream.eof()) {
in_stream.get(letter);
if (letter == 'z') {
letter = 'a';
}
if (letter == 'Z') {
letter = 'A';
}
if (letter == ' ') {
letter = letter;
}
else {
letter = letter + 1;
}
out_stream << letter;
}
}
}
Shift ciphers can be achieved using this way:
while(!in_stream.eof()) {
if (letter>='a' && letter<='Z')
letter = (letter+1)%'Z' + 'a';
out_stream << letter;
}
Reduce redundancy from your code and make it as compact as possible, there are so many useless conditions in your code.
The main logic lies in ciphering characters from a...Z, you cannot predict other characters in text file such as \n \0 etc, so they shouldn't be dealt with at all.
I can suggest this piece of code
while(!in_stream.eof()) {
if ((letter>='A' && letter<='Y')|| (letter>='a' && letter<='y'))
letter = (letter+1);
else if(letter== 'Z' || letter== 'z')
letter =(letter-25);
out_stream << letter;
}
What it's supposed to do
My piglatin program is supposed to take a phrase from user input and output it into pig latin. Basically it would turn a word such as "hello" into "ellohay".
My problem
When I input hello my man the output is ellohay y man an may and when I just input hello my the output is ellohay y may. As you can see, after it translates the first word successfully, it struggles on the second word. It places a space after the y and mayI cannot figure out for the life of me why this keeps happening. The output is even stranger when I input more than two words, as shown above. What I want to happen is for it to output ellohay ymay anmay when I input hello my man. Code is below. Thanks!
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void phrase_Parser(string); // Goes through phrase and looks for ' ' to then pass to pigLatin_Translator()
void pigLatin_Translator(string);
int main()
{
string phrase; //used for user word or phrase to be translated to piglatin
cout << "Enter any word: ";
getline(cin, phrase);
phrase_Parser(phrase);
return 0;
}
void phrase_Parser(string phrase) {
int startCount = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase[i] == ' ') {
string word = phrase.substr(startCount, i);
startCount = (i + 1); // decides where to start the word next time it is ran through
pigLatin_Translator(word); // runs word through translator
}
}
}
void pigLatin_Translator(string word) {
string partOne;
string partTwo;
for (int x = 0; x < word.length(); x++) {
if (word[0] == 'q' && word[1] == 'u') {
cout << word.substr(2, word.length()) << word.substr(0, 2) << "ay ";
break;
}
else if ((word[x] == 'a') || (word[x] == 'e') || (word[x] == 'i') || (word[x] == 'o') || (word[x] == 'u') || (word[x] == 'y')) {
partOne = word.substr(x, word.length()); //from first vowel to end of word
partTwo = word.substr(0, x); // from first letter to first vowel, not including the vowel
cout << partOne << partTwo << "ay "; // adding "ay" to the end of the word
break;
}
}
}
Your problem is in the line string word = phrase.substr(startCount, i);
You are using substr incorrectly. The second argument to substr is the length of the substring you wish to extract. Replace i with i-startCount and you should be good to go.
Alternatively, search for a nicer way to split strings. There are a number of options that are much easier than doing it manually.
Slight issue. (Not using toupper() and tolower() functions) I understand what converting to uppercase and lowercase using numerical values is but following my C++ book, why is the conversion at the end of this statement and not before?:
if (letter >= 'A') //test for 'A' or larger
if (letter <= 'Z') //test for 'Z' or smaller
{
cout << endl
<< "You entered a capital letter."
<< endl;
letter += 'a' - 'A'; //Convert to lowercase
return 0;
}
if (letter >= 'a') //test for 'a' or larger
{
if (letter <= 'z') //test for 'z' or smaller
{
cout << endl
<< "You entered a small letter."
<< endl;
return 0;
}
}
Why would it convert the uppercase to lowercase at this point of code execution since the second if statement deals with lowercase input?
The given snippet could be the body of the function:
int convert(char& letter)
{
if (letter >= 'A' && letter <= 'Z')
{
letter += 'a' - 'A';
return 0; // go out of this function...
}
else if (letter >= 'a' && letter <= 'z')
{
letter += 'A' - 'a';
return 0; // go out of this function...
}
return -1; // it wasn't a letter as we expected
}
Note, that there's a possible path that doesn't match none of these 2 situation. Let's say that letter is '?', since you're returning int value, there should be an indication that something is wrong (it's up to you how you deal with error handling).
Possible usage of your this function could look like this:
char letter = '!';
if (convert(letter) == 0)
// success ...
else
// error ...
If the question is really about leaving the scope of function, then this question could be helpful too:
How to break out of a function
Concrete example:
void convertLetterAndPrintResult(char& letter)
{
if (convert(letter) == 0)
std::cout << letter << std::endl;
else
std::cout << "ERROR: '" << letter << "' is not valid character!" << std::endl;
}
int main()
{
char letter = '!';
convertLetterAndPrintResult(letter);
letter = 'g';
convertLetterAndPrintResult(letter);
letter = 'L';
convertLetterAndPrintResult(letter);
}
Output:
ERROR: '!' is not valid character!
G
l
Because there's a return 0; statement in the first part. If the original character was uppercase, the control flow doesn't even reach the second nested if () { if () { } } part.
Why would it convert the uppercase to lowercase at this point of code
execution since the second if statement deals with lowercase input?
That is because
return 0
means that the function is finished. The lines
if (letter >= 'a') //test for 'a' or larger
{
if (letter <= 'z') //test for 'z' or smaller
{
cout << endl
<< "You entered a small letter."
<< endl;
return 0;
}
}
will not be executed if letter was originally an upper case letter. It would print out "You entered a capital letter.", then convert it to lower case, then exit.
why is the conversion at the end of this statement and not before?
It would make no difference if the conversion were before the cout statement.