It keeps skipping the else part of my statement. I just want it to print out of the invalid line if all the other restrictions are not met.
import java.util.Scanner;
public class Program_3
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a password: ");
String str = input.nextLine();
boolean lowerCase = false;
boolean upperCase = false;
boolean number = false;
char y;
for (int i = 0; i < str.length(); i++)
{
y = str.charAt(i);
if(Character.isUpperCase(y))
{
upperCase = true;
}
else if(Character.isDigit(y))
{
number = true;
}
else if(Character.isLowerCase(y))
{
lowerCase = true;
}
}
if (lowerCase == true)
{
if (upperCase == true)
{
if (number == true)
{
if (str.length() >= 8)
{
System.out.println("Verdict:\t Valid");
}
}
}
}
else
System.out.println("Verdict:\t Invalid");
}
}
why does it skip and not print the invalid line when all ifs are not met?
The else in your code relates only to the outermost if.
So it will only be executed if lowerCase == false.
To fix this logic, combine all three conditions in a single if, i.e.:
if (lowerCase == true && upperCase == true && number == true && str.length() >= 8)
{
System.out.println("Verdict:\t Valid");
}
else
System.out.println("Verdict:\t Invalid");
Side note, booleans don't require explicit comparison to true, so you can write it shorter:
if (lowerCase && upperCase && number && str.length() >= 8)
The else condition is placed in the wrong place, it'll only be reached if the lowerCase condition is false. And anyway, we can simplify and combine all the ifs in a single condition, what you meant to say was this:
if (lowerCase && upperCase && number && str.length() >= 8) {
System.out.println("Verdict:\t Valid");
} else {
System.out.println("Verdict:\t Invalid");
}
This code can b be simplified to show control-flow:
if(lowerCase == true)
{
//lowerCase == true -> execute this code
if( upperCase == true)...
}else
//lowerCase == false -> execute this code
...
The inner if-statements (which are exclusive btw.) don't execute the outer else-statements, if the condition is false. The logical correct version of your code would be:
if(lowerCase && upperCase && isNumber && str.length() > 8)
System.out.println("Verdict:\t Valid");
else
...
Your test password contains at least one lowercase character. As long as it does, the else statement will never execute. To test "if all conditions are true ... else ..." try the follwing:
if (lowerCase && upperCase && number && str.length >= 8) {
// password ok
} else {
// password not ok
}
By the way, as you can see I don't use lowerCase == true since it's not needed, lowerCase already is a boolean.
Related
I am attempting to use a helper method that checks if all characters in a word are vowels.
I am then attempting to create another method that uses a Scanner as a parameter and will continuously ask the user to enter a word until the user enters a word that contains all vowels. (The word doesn't have to be a word, it could be ieuo).
I cannot figure out how to have the method verify the scanner is all vowels and then return the correct output.
Here is what I have so far:
import java.util.*;
public class LabFinish {
public static void main(String[] args) {
System.out.println("Enter a word: ");
Scanner scan = new Scanner(System.in);
askForWords(scan);
public static boolean isAllVowels(Scanner scan) {
String str = scan.nextLine();
for (int i = 0; i <= str.length(); i++)
if ((str.charAt(i) == 'a') ||
(str.charAt(i) == 'e') ||
(str.charAt(i) == 'i') ||
(str.charAt(i) == 'o') ||
(str.charAt(i) == 'u')) {
return true;
}
return false;
}
public static String askForWords(Scanner scan) {
if (isAllVowels(scan) == true) {
return "Finally all vowels, we are done.";
}
else {
System.out.println("Enter a word: ");
Scanner scan1 = new Scanner(System.in);
if (isAllVowels(scan1) == true) {
return "Finally all vowels, we are done.";
}
else {
return "Enter a word";
}
}
}
Any help with this would be greatly appreciated.
Thank you.
A couple of things that should help you forward:
Merely returning a String from a method doesn't output it anywhere. So, replacing
askForWords(scan);
with
System.out.println(askForWords(scan));
in main() will show you the result of the method.
While you're checking for vowels, you need to iterate through the whole word, instead of stopping at the first vowel you encounter. Using your current code, the easiest fix is to invert the values of the return statements and the truth value of the comparison:
for (int i = 0; i < str.length(); i++) {
if ( !( // <- if the string has any other characters than the ones below, return a falsey
(str.charAt(i) == 'a')
|| (str.charAt(i) == 'e')
|| (str.charAt(i) == 'i')
|| (str.charAt(i) == 'o')
|| (str.charAt(i) == 'u'))) {
return false;
}
}
return true;
You also have some other issues, such as the code only running for a maximum of two input strings (you'd need a loop instead of a single if-else), but these are a bit off-topic for this question.
The below code is supposed to tell the user whether his input is a vowel or consonant or digit less than 1. The program however returns "Vowel" for all capital letters including consonants and whenever a digit is entered "Consonant" is returned. Ex - if a is entered, result = vowel. If b, result = Consonant. If B, result = Vowel (should be Consonant). If 1, result = Consonant(should be Digit) . Any advice would be greatly appreciated. Thanks.
package checkVowelorConstantorNumber;
import java.util.Scanner;
public class Main {
public static void main (String [] args) {
Scanner inp = new Scanner (System.in);
boolean tf = false;
while(tf == false) {
System.out.println("Enter a character which is a - z or A - Z or
less than 1");
char cha = inp.next().charAt(0);
inp.nextLine();
if(Character.isLetter(cha) && cha == 'a'||cha == 'e' || cha == 'i' || cha == 'o' || cha == 'u' || Character.isUpperCase(cha)) {
System.out.println("Vowel");
}
else if(Character.isLetter(cha) && cha != 'a'|| cha != 'e' || cha != 'i' || cha != 'o' || cha != 'u' || Character.isUpperCase(cha)) {
System.out.println("Consonant");
}
else if(Character.isDigit(cha) && cha <= 1 ) {
System.out.println("Digit");
}
else System.out.println("Invalid character");
}
}
}
Your if statement first checks if the given character is a letter and not an a, 1 is neither so that is false, then it checks if 1 is not equal to 'e' causing that statement to be true, thus printing 'Consonant'. You have to make the check for isLetter for every comparison. Therefore i would recommend something like this:
if(Character.isLetter(cha)) {
// Check for vowel or consonant based on letters
} else if(Character.isDigit(cha) && cha <= '1') {
System.out.println("Digit");
} else {
System.out.println("Invalid character");
}
You also should make the if statement for consonant use && instead of ||, since it should be none of the specified chars.
Pay close attention to logical ands (&&), logical ors (||) and parentheses. Consider the following, modified from your code with some comments.
char cha = inp.next().charAt(0);
inp.nextLine();
if (cha.isLetter()) {
// convert to uppercase to simplify the if
char uc = cha.toUpperCase();
if (uc == 'A' || uc == 'E' || uc == 'I' || uc == 'O' || uc == 'U') {
// it's a vowel
} else {
// it's a letter that isn't a vowel (consonant)
}
} else {
// it's not a letter
if (cha.isDigit() && cha < '1') {
// but it is a digit less than 1
} else {
// it's something else (digit not less than '1' or not a digit)
}
}
import java.util.Scanner;
public class Exercise6_18 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Password rules:\n"
+ "Password must have at least eight characters\n"
+ "Password must consist of only letters and digits\n"
+ "Password must contain at least two digits\n"
+ "Enter a password:");
String pWT = sc.next();
passWordIsValid(pWT);
}
public static void passWordIsValid (String password) {
boolean passWordIsValid;
if (password.length() < 8) {
passWordIsValid = false;
}
else if (password.indexOf(0) == -1 && password.indexOf(1) == -1
&& password.indexOf(2) == -1 && password.indexOf(3) == -1
&& password.indexOf(4) == -1 && password.indexOf(5) == -1
&& password.indexOf(6) == -1 && password.indexOf(7) == -1
&& password.indexOf(8) == -1 && password.indexOf(9) == -1) {
passWordIsValid = false;
}
else
passWordIsValid = true;
if (passWordIsValid == true)
System.out.print("Password is valid");
else if (passWordIsValid == false)
System.out.println("Password is invalid");
}
}
I am trying to write a program that prompts the user to enter a password that is at least 8 characters long, contains at least two digits and is comprised of only letters and digits but when I enter: password12 it says password is invalid. P.S. I know I haven't added the requirement for at least two digits in the method.
...else if (password.indexOf(0) == -1 && password.indexOf(1) == -1
&& password.indexOf(2) == -1 && password.indexOf(3) == -1
&& password.indexOf(4) == -1 && password.indexOf(5) == -1
&& password.indexOf(6) == -1 && password.indexOf(7) == -1
&& password.indexOf(8) == -1 && password.indexOf(9) == -1) {
passWordIsValid = false;
}...
What are you trying to achieve with this code? It doesn't make any sense at all. You probably want to loop over every character of the string instead while counting for every character if it is a digit (and you could "break;" out of the loop as soon as your count is >=2).
Also: Don't save passwords in strings... they will stay in the string pool for quite a while and can be read from memory by malicious programs. You can use a char[] instead.
If you do not want to use Regex, you can use a simple for loop and if statement, you may do something like this:
import java.util.Scanner;
public class PromptPassword {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Password rules:\n"
+ "Password must have at least eight characters\n"
+ "Password must consist of only letters and digits\n"
+ "Password must contain at least two digits\n"
+ "Enter a password:");
String pWT = sc.nextLine(); //read the entire line
passWordIsValid(pWT.trim()); // to remove leading spaces (if any)
}
public static void passWordIsValid (String password) {
boolean passWordIsValid = true;
int noOfDigits =0;
if (password.length() > 8) { // if it's less than 8 chars -> no need to continue
for(char c : password.toCharArray()){
if(Character.isDigit(c)){ // if it's a digit, increment
noOfDigits++;
}
else if(!Character.isAlphabetic(c)){ // if it's not a digit nor alphapet
passWordIsValid = false;
break;
}
}
}
if (passWordIsValid && noOfDigits>=2){
System.out.print("Password is valid");
}
else{
System.out.println("Password is invalid");
}
}
}
Test
Enter a password: abcd12 -> Password is invalid (less than 8)
Enter a password: abcde#123 -> Password is invalid (contains special char)
Enter a password: abcdefghi1 -> Password is invalid (less than 2 digits)
Enter a password: abcdefg12 -> Password is valid (9 in length and contains 2 digits and no special chars)
Your algorithm will not check whether there are at least two digits, and will not check that there are only printable characters and digits in it. Instead of checking for indexOf() you need to loop through all of the characters and count the number that are digits, and ensure each one is either a digit or an alphabetic character, keeping track of the number that are digits.
Use Regex to validate password. positive Lookahead does very good job at validating strings.
Example in java
public static void main(String[] args) {
String passwd = "aaZZa44#";
String pattern = "^(?=.*[0-9].*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}$";
System.out.println(passwd.matches(pattern));
}
(?=.*[0-9].*[0-9]) at least 2 digits.
(?=.*[a-z]) lower case a-z
(?=.*[A-Z]) upper case A-Z
{8,} 8 digit in length
I have following problem:
The user has to put his name correctly in my program:
the name only contain letters, hyphens "-" and blanks " "
the first letter should be a capital letter.
after a blank or hyphens should be followed by a capital letter.
For example only this form should be accepted by the program:
"Name" or "Firstname-Secondname" or "Firstname Secondname".
The 3rd point doesn't work in my code:(
My Java code:
public class Test {
private static Scanner scanner = new Scanner(System.in);
private static String name;
public static void main(String[] args) {
boolean check = false;
check = checkName();
System.out.println("Check= "+check);
output(check);
}
public static void output(boolean check) {
if (check == false) {
System.out.println("Fehler");
}
if(check == true) {
System.out.println("Dein Name ist: "+name);
}
}//End output()
public static boolean checkName() {
System.out.print("Name: ");
name = scanner.nextLine();
boolean check = false;
if(name.charAt(0) >= 'A' && name.charAt(0) <= 'Z') {
for(int i=1; i < name.length(); i++) {
if (name.charAt(i) >= 'a' && name.charAt(i) <= 'z') {
check = true;
} else if (name.charAt(i) == '-') {
i++;
if(name.charAt(i) >= 'A' && name.charAt(i) <= 'Z') {
check = true;
} else {
check = false;
}
} else if (name.charAt(i) == ' ') {
i++;
if(name.charAt(i) >= 'A' && name.charAt(i) <= 'Z') {
check = true;
} else { check = false;
}} else {
check = false;
break;
}
}
} return check;
}//End checkName()
Can someone help please?
This looks like a good place to use a regular expression. What about the following example:
String name = scanner.nextLine();
if (Pattern.compile("^[A-Z][a-z]*(?:(?: |-)[A-Z][a-z]*)?$").matcher(name).find()) {
// Valid Name
}
This checks the variable name against a regular expression to see if it matches. To explain the regular expression:
^ This means start of string.
[A-Z][a-z]* This means an uppercase letter followed by zero or more lowercase letters.
((?: |-)[A-Z][a-z]*)? This means followed by a space or hyphen with an uppercase followed by an optional lowercase character - this section is optional as the group is followed by a ?.
$ This means end of string.
You can also use String.matches() which is simpler, instead of Pattern.compile().matcher().
I'm having difficulty ensuring that doubles are validated correctly in my program. A user can enter an amount to deposit into the account, which should be a double (I know, it's not what I should be using, but it's part of the assignment guidelines). Theoretically, the user should be able to deposit any amount- not just £30, but say, £15.23.
This is the validation I currently have, which allows numbers, but prevents the entry of a full stop, which creates a number of problems.
Here is the code I have so far:
public static String getBalanceValidation()
{
//Allow user input capabilities
Scanner input = new Scanner (System.in);
//Declare variables needed for validation
double dblInput = 0; //dblInput is set as 0
String strNumber = ""; //strNumber is blank
boolean bolSuccessful, bolNumeric;
int intCount;
char charLetter;
do
{
//set bolSuccessful and bolNumeric as true
bolSuccessful = true;
bolNumeric = true;
try //try user input
{
System.out.println("Enter the balance to be deposited: "); //User prompt
strNumber = input.next(); //User input as string
dblInput = Double.parseDouble(strNumber) ; //String input converted to double
}// end of try
catch (NumberFormatException e) //NumberFormatException disallows letters or symbols in value
{
System.out.println("Deposit value cannot contain letters!"); //Error message
bolSuccessful = false; //set bolSuccessful as false
continue; //Return to try
}//end of number format catch
//create for loop which checks each character throughout the string
for (intCount = 0; intCount < strNumber.length(); intCount++)
{
charLetter = strNumber.charAt(intCount); //charLetter is the alphanumeric value of a character in the string at the point dictated by intCount
if (!(charLetter >= '0') && (charLetter <= '9' ) //if charLetter is not between 0 and 9
|| (charLetter == '.')) //or charLetter is not a full stop
{
bolNumeric = false; //Set bolNumeric as false
}//end of if construct
}//end of for loop
if (!bolNumeric) //if bolNumeric is false
{
System.out.println("Incorrect input format! The balance must be numbers only!"); //Error message
bolSuccessful = false; //Set bolSuccessful as false
}//end of if construct
}while (!bolSuccessful); //While bolSuccessful is false, return to top
return strNumber; //return strNumber to be used in main method
//end of do method
}//end of getBalanceValidation method
I'm not sure whether it's because I've used NumberFormatException (is there something else for double?)
Many thanks
You have 2 errors in your boolean expression :
if (!(charLetter >= '0') && (charLetter <= '9' ) || (charLetter == '.'))
This condition is equivalent to :
if ((charLetter < '0') && (charLetter <= '9' ) || (charLetter == '.'))
Which can be simplified to :
if ((charLetter < '0') || (charLetter == '.'))
So the ! should be applied to the first two parts of the expression :
if (!( (charLetter >= '0') && (charLetter <= '9') ) || (charLetter == '.'))
Moreover, since . is not a number, this expression is equivalent to :
if (!( (charLetter >= '0') && (charLetter <= '9') ))
You probably meant && not || :
if (!( (charLetter >= '0') && (charLetter <= '9' ) ) && (charLetter != '.'))
Which means if(not_a_number AND not_a_full-stop)
You can double number = input.nextDouble(); instead of strNumber = input.next();. This would allow you to input the number directly as double instead of String.
You would have to handle InputMismatchException in your catch block, and you are good to go. You won't need to validate to check the inclusion of ..
It would be much easier using a regex:
bolNumeric = strNumber.matches("[1-9][0-9]*(\\.[0-9]{1,2})?");
Explanation: The first number has to be within 1-9. Then as many as you want (including none) other numbers may follow. This is optionally followed by a dot, and then at least one, max 2 more digits.