Error while doing character to character matching in java - java

I'm doing a character to character comparison and checking for some special characters present or not, using the below code, but its not working. Any idea why "ch" comparison with special character doesn't work?
Scanner sc= new Scanner(System.in);
System.out.print("Enter the password to validate: ");
String pass = sc.nextLine();
char ch=0;
for(int i=0;i<pass.length();i++)
{
ch = pass.charAt(i);
if(ch !='$' || ch !='#' || ch !='#' || ch !='%' || ch !='&')
splchar++;
}
if(splchar == pass.length())
System.out.println("Invalid Password");
else
System.out.println("Valid Password");

Your condition is always true
ch !='$' || ch !='#' || ch !='#' || ch !='%' || ch !='&'
is the same has
! (ch == '$' && ch =='#' && ch =='#' && ch =='%' && ch =='&')
Since a value can't be $ and # at the same time, this will always be !(false) and then true.
You want
ch =='$' || ch =='#' || ch =='#' || ch =='%' || ch =='&'
to check if it is one of those character.
Alternative - Array
You can simplified your logic using an
char[] needed = {
'#', '$', '#', '%', '&'
};
Then you just need to search in that array for a match, since Arrays provide those method, you just need to check it with Arrays.binarySearch(needed, ch), it will return the position of the char matching or -1 is nothing is found so you can simplified with
if(Arrays.binarySearch(needed, ch) < 0)
splchar++;
Like Joop Eggen said, this need to be a sorted array to work, so you can use
`Arrays.sort(needed)`
Of course, this become a bit complicated just to search for character, again, Joop Eggen proposed a simplified version that work for char : "#$#%&".indexOf(ch) != -1
Alternative - Regex
You can use a Regex to match it with your String directly. But I will let you do some research on that logic, this is out of context.

Related

How to write a continuous (infinite loop) program in JAVA to verify vowel?

Write a program that asks the user to type a vowel from the keyboard. If the character entered is a vowel, display “OK”; if it is not a vowel, display an error message. Be sure to allow both uppercase and lowercase vowels. The program continues until the user types ‘!’.
I have written the program but I need it to loop. I wrote a code where it only accepts one input and I don't know what I am supposed to use for the input for char.
Scanner input = new Scanner(System.in);
System.out.println("Enter an alphabet between a to z; Enter ! to stop");
int myChar;
myChar = input.nextInt();
while (myChar <= 'z') {
if (myChar == 'a' || myChar == 'e' || myChar == 'i' ||myChar == 'o' || myChar == 'u' ) {
System.out.println(myChar + " OK");
} else {
System.out.println(myChar + " is not vowel");
}
}
You're almost there :)
A small error that you've made is that you've limited your scanner to only reading integers.
You've also declared myChar to an int. Since it is a character, you can declare it like:
char myChar = input.next().charAt(0);
A scanner has many functions, and some are specific to certain variable types
.nextInt() will only read integers.
nextDouble().will read doubles
.nextLine() will read till the end of the current line
Thus, as I mentioned above, you can simply use .next().charAt(0)
First, you need to put the declaration before you give it a value, so it should be
int myChar;
myChar = input.nextInt();
Second, you are reading a char, so it should not be int myChar...
char myChar;
myChar = input.next().charAt(0);// Since there no nextChar() in scanner
Third, your while loops is NEVER going to stop, since the value of myChar is not changed in the while loop,
Fourth, you did not allow both uppercase and lowercase vowels, you only allowed lowercase vowels
Fifth, add the statement "! to stop", I mean, I'm sure you don't want "! is not a vowel" to be printed, right?
So this is what it should look like:
Scanner input= new Scanner(System.in);
System.out.println("enter alphabet between a & z, ! to stop");
char myChar;
myChar = input.next().charAt(0);
while(('a' <= myChar && myChar <= 'z') || ('A' <= myChar && myChar <= 'Z')) {
if(myChar == 'a' || myChar == 'e' || myChar == 'i' ||myChar == 'o' || myChar == 'u' || myChar == 'A' || myChar == 'E' || myChar == 'I' || myChar == 'O' || myChar == 'U'){
System.out.println(myChar + " OK");
}else if(myChar == '!'){
break;
}else{
System.out.println(myChar + " is not vowel");
}
System.out.println("Enter again:");
myChar = input.next().charAt(0);
}
You code is almost correct but you are missing few very important parts.
Declaration int myChar; should be written before initialization myChar = input.nextInt();
You are willing to read a char so you should declare myChar variable with data type char and not int.
Your while-loop condition does not satisfy the need. Because you are just using one end of the range of alphabet but missing the other end and hence it will not generate desired boolean result.
Approach to reach solution for your problem:
Read a string from user using scanner.next() method.
Convert the string to lower case to handle upper and lower case vowels.
Take the first character from the read string input by using the method string.charAt(0) to convert String into char and save it to myChar.
Start a while-loop that will keep iterating until myChar == '!'.
Inside the loop, first check if myChar is a vowel. If true, print "OK".
If myChar is not a vowel, check if myChar fall in range of an alphabet or not. If true, print "Not a vowel".
If myChar does not fall in the range of English alphabets then print "You entered an incorrect alphabet" and prompt for new value.
Finally, if myChar is !, then the condition for while-loop becomes false and the program stops.
Here is the full code:
Scanner input = new Scanner(System.in);
System.out.println("Enter an alphabet between 'a' to 'z'; Enter '!' to terminate");
/*
* input.next() reads a string from Scanner's input stream until it finds a space or endOfLine.
* string.toLowerCase() converts any English alphabet in a string to lower case and return the new string. For example, "Hello World 21F" becomes "hello world 21f".
* string.charAt(0) returns the character of a string at index 0; 1st position.
*/
char myChar = input.next().toLowerCase().charAt(0);
while (myChar != '!') {
if (myChar == 'a' || myChar == 'e' || myChar == 'i' ||myChar == 'o' || myChar == 'u') {
System.out.println(myChar + " OK");
} else if (myChar >= 'a' && myChar <= 'z') {
System.out.println(myChar + " is not vowel");
} else {
System.err.printf("You entered an incorrect alphabet '%c'. ", myChar);
}
System.out.println("Enter an alphabet between 'a' to 'z'; Enter '!' to terminate");
myChar = input.next().toLowerCase().charAt(0);
}

Trying to create a case to identify multiple characters

I'm attempting to create a case that identifies every use of 'E' or 'e' in a string but am unsure how to format it correctly.
I've attempted separating 'E' and 'e' as seperate variables but this doesn't seem to work
The output should tell the user how many uses of 'e' or 'E' are in the string they entered, but I am just getting formatting errors. Additionally, if I limit it to either just 'e' or 'E' the program is able to work, however, I get a long string of numbers from it being counted in my for loop, is there any way to just display the final number from my for loop?
case 3: String phrase;
phrase = scan.nextLine();
System.out.println("What is your sentence");
phrase = scan.nextLine();
int numOfE = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == 'e' or == 'E') {
numOfE++;
}
System.out.println(numOfE);
}
Change:
if (phrase.charAt(i) == 'e' or == 'E')
to
if (phrase.charAt(i) == 'e' || phrase.charAt(i) == 'E')
Also, move the line:
System.out.println(numOfE);
outside one more set of brackets. In total, it should look something like:
case 3: String phrase;
phrase = scan.nextLine();
System.out.println("What is your sentence");
phrase = scan.nextLine();
int numOfE = 0;
for (int i = 0; i < phrase.length(); i++) {
char ch = phrase.charAt(i);
if (ch == 'e' || ch == 'E') {
numOfE++;
}
}
System.out.println(numOfE);
If you are using Java 8, then this is another approach
long count = phrase.chars().filter(ch -> ch == 'e' || ch == 'E' ).count();

How do I count number of spaces, vowels, and characters?

import java.util.*;
import java.lang.String;
public class counter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int space = 0,vowel = 0,chara = 0,i;
System.out.println(" Enter String ");
String s =in.nextLine();
for( i = 0; i < s.length(); i++)
{
char ch = in.next().charAt(i);
if(ch == ' ')
space++;
if(ch == 'e' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowel++;
else
chara++;
System.out.println("Number of Vowels = "+vowel);
System.out.println("Number of Spaces = "+space);
System.out.println("Number of Char = "+chara);
}
}
}
What is the problem? I have put three counters to count. I am coding in Eclipse and whenever I check the console I am not able to count the characters. It is just accepting inputs and not doing anything else.
Remove char ch = in.next().charAt(i);, and replace the other instances of ch with s.charAt(i)
The first charAt check should also be a, you have e twice.
Then move System.out.println... outside of the loop.
Online Demo
Just a couple of typo errors. Change your code with,
String s = in.nextLine().toLowerCase();
And
char ch = s.charAt(i);
And
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
In your code you are using lowercase letters to compare with the user input. So you should convert the user input to lower case first. Your current code ignores all uppercase vowels(E, A, I ...). Use toLowerCase().
By using in.next() the Scanner is waiting for an input. Since you have already taken an input using nextLine() you can use that.
Next one is obviously a typographical error. Vowels are A, E, I, O, U.
You should change s = in.next().charAt(i);to String s =in.nextLine() and put System.out.printlnpart outside of for loop.
Also there is double 'e' (with the help of #Ted Hopp):
ch == 'e' || ch == 'e' to ch == 'e' || ch == 'a'
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int space = 0,vowel = 0,chara = 0,i;
System.out.println(" Enter String ");
String s =in.nextLine();
for( i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
if(ch == ' ')
space++;
if(ch == 'e' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowel++;
else
chara++;
}
System.out.println("Number of Vowels = "+vowel);
System.out.println("Number of Spaces = "+space);
System.out.println("Number of Char = "+chara);
}

Checking if input is correct type java

System.out.println("What letter should the word begin with?");
char letter = input.next().charAt(0);
if(letter != ''){
throw new InputMismatchException("Please input a letter");
}
I want to check to see if the user input anything besides a string/char. If they have I want to throw an exception that says the input is wrong. This is my current code but as it stands it does not compile.
You can check whether letter is a letter like this:
if ((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z'))
Actually, Scanner has this handy overload of next(String pattern) that throws an InputMismatchException automatically if the input does not match a pattern:
char letter = input.next("[a-zA-Z]").charAt(0);
[a-zA-Z] is the pattern used here. It accepts any character from a to z or from A to Z.

Why isn't the first character uppercase?

I have found syntax that is supposed to change the first character from a lowercase letter to an uppercase letter.
For some reason my program won't! When I type a 'm' instead of 'M'.
What am I doing wrong here?
public static void main(String[] args) {
System.out.print("Enter two characters: ");
Scanner input = new Scanner(System.in);
String twoChar = input.nextLine();
if(twoChar.length() > 2 || twoChar.length() <= 1){
System.out.println("You must enter exactly two characters");
System.exit(1);
}
char ch = Character.toUpperCase(twoChar.charAt(0));
if(twoChar.charAt(0) == 'M'){
if(twoChar.charAt(1) == '1'){
System.out.println("Mathematics Freshman");
}else if(twoChar.charAt(1) == '2'){
System.out.println("Mathematics Sophomore");
}else if(twoChar.charAt(1) == '3'){
System.out.println("Mathematics Junior");
}else if(twoChar.charAt(1) == '4'){
System.out.println("Mathematics Senior");
}
}
Instead of
if(twoChar.charAt(0) == 'M'){
use
if(ch == 'M'){
You are getting the uppercased character, but then not using it.
You are assigning the upper case version of the character to a variable ch, and then you are not checking ch; you are checking the character in the string again. That character is the same as it was before: it is not changed.
So instead of checking:
if (twoChar.charAt(0) == 'M') {
check:
if (ch == 'M') {
Not using the local variable
You aren't using the char ch you uppercased here,
char ch = Character.toUpperCase(twoChar.charAt(0));
if(twoChar.charAt(0) == 'M'){
you might fix it by using the local variable ch like
char ch = Character.toUpperCase(twoChar.charAt(0));
if (ch == 'M') {
or by placing the toUpperCase call in-line like
// char ch = Character.toUpperCase(twoChar.charAt(0));
if (Character.toUpperCase(twoChar.charAt(0)) == 'M') {
or using a logical-or like
char ch = twoChar.charAt(0);
if (ch == 'M' || ch == 'm') {

Categories