Java Loops - Password requirements [duplicate] - java

This question already has answers here:
Get string character by index
(13 answers)
Closed 8 months ago.
Websites commonly require a password that satisfies several requirements. Write a program that checks if an input string satisfies the following (error message is shown for each):
At least 8 characters (Too short)
At least one letter (Missing letter)
At least one number (Missing number)
At least one of these special characters: !, #, % (Missing special)
Output OK, or all related error messages (in above order). If the input string is "Hello", the output is:
Too short
Missing number
Missing special
Hints:
Declare a boolean variable for each requirement.
Use a for loop to visit each character, setting the corresponding boolean to true if satisfied (length is done differently though).
Use the functions Character.isLetter() and Character.isDigit() to detect if a character is a letter or a number.
This is what I have so far for my Java program, but I keep getting errors. Thanks for the help.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String newString;
boolean atLeastEightCharacter;
boolean atLeastOneLetter;
boolean atLeastOneNumber;
boolean atLeastOneSpecialCharacter;
newString = scnr.nextLine();
atLeastEightCharacter = false;
atLeastOneLetter = false;
atLeastOneNumber = false;
atLeastOneSpecialCharacter = false;
if (newString.length() >= 8) {
atLeastEightCharacter = true;
for (int i = 0; i <newString.length(); i++) {
if (Character.isLetter(i)) {
atLeastOneLetter = true;
}
if (Character.isDigit(i)) {
atLeastOneDigit = true;
}
if (newString(i) == '!' || newString(i) == '#' || newString(i)
== '%') {
atLeastOneSpecialCharacter = true;
}
}
}
if (atLeastEightCharacter == false) {
System.out.println("Too short");
}
if (atLeastOneLetter == false) {
System.out.println("Missing letter");
}
if (atLeastOneDigit == false) {
System.out.println("Missing number");
}
if (atLeastOneSpecialCharacter) {
System.out.println("Missing special");
}
}
}

the problem is that you're not checking string's symbols, but indexes, variable i is not char, but integer index
here is fixed version:
for (int i = 0; i <newString.length(); i++) {
char c = newString.charAt(i);
if (Character.isLetter(c)) atLeastOneLetter = true;
if (Character.isDigit(c)) atLeastOneDigit = true;
if (c == '!' || c == '#' || c == '%') atLeastOneSpecialCharacter = true;
}

Related

How to eliminate all scenarios where there is no content in the string? For example : "" vs " " And checking if the given word is an isogram

public class isogram {
public static boolean isIsogram(String str) {
// ...
boolean flag = false;
String st = str.toLowerCase();
String checker = String.valueOf(st.charAt(0));
// check if the string is empty and return false
if (st == ""){
return flag;
}
// for each char in the string, check if it lies in the a-z range
// and that it obeys the isogram conition (no repetitions)
for(int i=1; i<st.length()-1 ; i++){
boolean cond_check = !checker.contains(String.valueOf(st.charAt(i)));
if (st.charAt(i) >= 'a' && st.charAt(i) <= 'z' && cond_check ){
flag = true;
}
else{
flag = false;
break;
}
checker = checker + st.charAt(i);
}
return flag;
}
}
I'm trying to check if the given word is an isogram (no repetitions and numbers). Not able to figure what the issue is. And also while eliminating the empty string, I think I have to try to avoid " " (empty strings with spaces as well because they count as characters). How to do that?

Registering an invalid piece of data from a pattern

I need to use a six letter word and if it has a sequence of letter number letter number letter number, then it will be a valid piece of data. Otherwise, it will be considered invalid. The problem with my code is, it always runs it as valid. Here is my code:
vstatus=false;
char a=pcode.charAt(0);
char b=pcode.charAt(1);
char c=pcode.charAt(2);
char d=pcode.charAt(3);
char e=pcode.charAt(4);
char f=pcode.charAt(5);
if(!Character.isLetter(a)) vstatus=true;
if(!Character.isDigit(b)) vstatus=true;
if(!Character.isLetter(c)) vstatus=true;
if(!Character.isDigit(d)) vstatus=true;
if(!Character.isLetter(e)) vstatus=true;
if(!Character.isDigit(f)) vstatus=true;
if (vstatus=true)
{
System.out.println(convertUpperCase(pcode)+" is a valid postal code");
}
if (vstatus=false)
{
System.out.println(convertUpperCase(pcode)+" is not a valid postal code");
}
I gues this would be shorter code for your problem:
String pcode = "aza2a3";
String regex = "[A-Za-z]{1}[\\d]{1}[A-Za-z]{1}[\\d]{1}[A-Za-z]{1}[\\d]{1}";
boolean matches = pcode.matches(regex);
System.out.println(matches);
matches is true if your string is in form that you need and false if i does not match your required string
In your code, even if one character is correct and all the others are wrong, you make it true. You need to confirm that all the characters are correct. Use &&.
String pcode = "i8i8i8";
char a=pcode.charAt(0);
char b=pcode.charAt(1);
char c=pcode.charAt(2);
char d=pcode.charAt(3);
char e=pcode.charAt(4);
char f=pcode.charAt(5);
if (Character.isLetter(a) && Character.isDigit(b) && Character.isLetter(c) && Character.isDigit(d) && Character.isLetter(e) && Character.isDigit(f)) {
System.out.println("valid");
} else {
System.out.println("not a valid postal code");
}
Or, in a loop:
String pcode = "i8i8i8";
boolean flag = true;
for (int i = 0; i < pcode.length(); i++) {
if (!(i % 2 == 0 && Character.isLetter(pcode.charAt(i)) || Character
.isDigit(pcode.charAt(i)))) {
flag = false;
}
}
if (flag) { System.out.println("valid"); }
else { System.out.println("not valid"); }
Ideally, extract the code into a method:
static boolean isPcodeValid(String s) {
for (int i = 0; i < s.length(); i++) {
if (!(i % 2 == 0 && Character.isLetter(s.charAt(i)) || Character
.isDigit(s.charAt(i)))) {
return false;
}
}
return true;
}
Or, use some Java8+ features:
static boolean isPcodeValid(String s) {
return IntStream.range(0, s.length())
.allMatch(i -> i % 2 == 0 && Character.isLetter(s.charAt(i)) || Character
.isDigit(s.charAt(i)));
}
Finally,
You may use this regex:
String r = [A-Za-z][\d][A-Za-z][\d][A-Za-z][\d]
if (pcode.matches(r)) {
// valid
} else {
// invalid
}
5 different ways, choose the one that suits you the best.

Method to Check Password in Java Not Working

I'm trying to write a method that returns if the string is or isn't a valid password in CodeHS.
It needs to be at least eight characters long and can only have letters and digits.
In the grader, it passes every test except for passwordCheck("codingisawesome") and passwordCheck("QWERTYUIOP").
Here's what I have so far:
public boolean passwordCheck(String password)
{
if (password.length() < 8)
{
return false;
}
else
{
char c;
int count = 0;
for (int i = 0; i < password.length(); i++)
{
c = password.charAt(i);
if (!Character.isLetterOrDigit(c))
{
return false;
} else if (Character.isDigit(c))
{
count++;
}
}
if (count < 2)
{
return false;
}
}
return true;
}
If anyone can help, I'd appreciate it. Thanks.
Try an approach using patterns (this is simpler than looping):
public boolean passwordCheck(String password)
{
return password!=null && password.length()>=8 && password.matches("[A-Za-z0-9]*");
}
Decent tutorial on regular expressions (that's where the A-Z magic comes from): http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
Assuming your requirement is as stated
It needs to be at least eight characters long and can only have letters and digits
Then there is no need to count digits. Simply check that the password is the minimum length, then loop over every character returning false if any are not a letter or digit. Like,
public boolean passwordCheck(String password) {
if (password != null && password.length() >= 8) {
for (char ch : password.toCharArray()) {
if (!Character.isLetterOrDigit(ch)) {
return false;
}
}
return true;
}
return false;
}
It's failing those tests because your code checks that the password must have at least 2 digits:-
if (count < 2)
{
return false;
}
And your test strings don't have any. Remove this piece of code and it should work. For a better way of doing it, see other answers.

isVowel() method with a character in a String

I have a text file with a bunch of words. One part of my program is supposed to, based on the user input, scan this list and insert into the output file the words that contain the requested number of vowels. I have a isVowel method that returns a boolean, but it doesn't seem to work--the output is just an empty list.
Here's the method:
public boolean isVowel(char c)
{
if(c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U')
{
return true;
}
else
{
return false;
}
}
}
Here's the part of the program where it is used:
public ArrayList<String> vowelHeavy(int n, int m)
{
int vowels = 0;
while(input.hasNextLine())
{
word = input.nextLine();
if (word.length() == n)
{
for(int i = 0; i < word.length(); i++)
{
if(isVowel(word.charAt(i)) == true)
{
vowels++;
}
}
if (vowels == m)
{
output.add(word);
}
}
word = input.nextLine();
}
return output;
}
Your biggest problem is you are not resetting you vowels counting variable when you test a new word. The value just keeps accumulating the total vowels in the file.
Change:
int vowels = 0;
while(input.hasNextLine()) {
...
to:
while(input.hasNextLine()) {
int vowels = 0;
...
As an aside, most of your code, including the isVowel() method, could be eliminated with a single line:
int vowels = word.replaceAll("[^aeiouAEIOU]", "").length();
This works by eliminating from the word all characters that aren't vowels; what's left are the vowels, so just take the length to get the count.
Theres a much easier way to write this code:
public boolean isVowel(char c){
return(your boolean tests);
}
2 things:
If the word.length() == n test is never true, then output is never changed. Please make sure that test is correct.
This statement exists at the top AND bottom of the while loop, causing you to ignore every other input line:
word = input.nextLine();

Writing a method to remove vowels in a Java String [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am a beginner of programming, and am writing a Java method to remove vowel in Strings, but I do not know how to fix this error: ";" expected :
public String disemvowel(String s) {
boolean isVowel(char c);
if (c == 'a') {
return true;
} else if if (c == 'e') {
return true;
} else if if (c == 'i') {
return true;
} else if if (c == 'o') {
return true;
} else if if (c == 'u') {
return true;
}
String notVowel = "";
int l = s.length();
for (int z = 0; z <= l; z++) {
if (isVowel == "false") {
char x = s.charAt(z);
notVowel = notVowel + x;
}
}
return notVowel;
}
String str= "Your String";
str= str.replaceAll("[AEIOUaeiou]", "");
System.out.println(str);
A much simpler approach would be to do the following:
String string = "A really COOL string";
string = string.replaceAll("[AaEeIiOoUu]", "");
System.out.println(string);
This will apply the regular expression, [AaEeIiOoUu] to string. This expression will match all vowels in the character group [AaEeIiOoUu] and replace them with "" empty string.
You've got a lot of syntax errors.
boolean isVowel(char c); - not sure what you're doing with this. if you want it as a separate method, separate it out (and don't place a semicolon after it, which would be invalid syntax.
else if if is invalid syntax. If you're doing an else if, then you only need the one if.
Even if the code would compile, for (int z = 0; z <= l; z++) will cause you to step off of the String. Remove the <= in favor of <.
isVowel == "false" is never going to work. You're comparing a String to a boolean. You want !isVowel instead.
Putting the syntax errors aside, think of it like this.
You have a string that contains vowels. You wish to have a string that doesn't contain vowels.
The most straightforward approach is to iterate over the String, placing all non-vowel characters into a separate String, which you then return.
Interestingly enough, the half-method you have there can accomplish the logic of determining whether something is or isn't a vowel. Extract that to its own method. Then, call it in your other method. Do take into account capital letters though.
I leave the rest as an exercise to the reader.
Here is your code, without changing any logic, but unscrambling the isVowel method:
public String disemvowel(String s) {
// Removed the "isVowel" method from here and moved it below
String notVowel = "";
int l = s.length();
for (int z = 0; z <= l; z++) {
// Note that the "isVowel" method has not been called.
// And note that, when called, isVowel returns a boolean, not a String.
// (And note that, as a general rule, you should not compare strings with "==".)
// So this area needs a lot of work, but we'll start with this
boolean itIsAVowel = isVowel(s.charAt(z));
// (I made the variable name "itIsAVowel" to emphasize that it's name has nothing to do with the method name.
// You can make it "isVowel" -- the same as the method -- but that does not in any way change the function.)
// Now take it from there...
if (isVowel == "false") {
char x = s.charAt(z);
notVowel = notVowel + x;
}
}
return notVowel;
}
// You had this line ending with ";"
boolean isVowel(char c) {
if (c == 'a') {
return true;
// Note that you coded "if if" on the lines below -- there should be only one "if" per line, not two
} else if if (c == 'e') {
return true;
} else if if (c == 'i') {
return true;
} else if if (c == 'o') {
return true;
} else if if (c == 'u') {
return true;
}
// You were missing this final return
return false;
}
(Yes, I know this should be a comment, but you can't put formatted code in a comment.)
You could try something like this:
public static String removeVowels(final String string){
final String vowels = "AaEeIiOoUu";
final StringBuilder builder = new StringBuilder();
for(final char c : string.toCharArray())
if(vowels.indexOf(c) < 0)
builder.append(c);
return builder.toString();
}

Categories

Resources