Searching a string for a non-letter character in a loop - java

So let's imagine we have this loop that obtains input from the user in the form of strings. With that input, what we want to do is set up a set of validations that will check if certain criteria are met. If all of these conditions are met, it'll complete the action in question. However; if it doesn't, it'll tell them the error and restart the process.
My question is about validating the existance (or non-existance) of a letter in a string. I have this program and for one of these validations, I need to check the entire string. If the string does not have at least one character that isn't a letter, I want to halt the action and explain that a non-letter character is required.
The problem is that I am not sure how I could replicate this in an expression in an if loop. Here's what I have so far.
public static changePassword() // Method that runs through the process of changing the password.
{
// Retrieving the current and new password from the user input.
System.out.println("Welcome to the change password screen.");
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your current password: ");
String currentPassword = keyboard.nextLine();
System.out.print("Please enter the new password: ");
String newPassword1 = keyboard.nextLine();
System.out.print("Please enter the new password again: ");
String newPassword2 = keyboard.nextLine();
// Validating the new password entry.
if (newPassword1.equals(newPassword2)) // Checking to see if the new password was entered exactly the same twice.
{
if (newPassword1.length() >= 6) // Checking to see if the new password has 6 or more characters.
{
if (**some expression**) // Checking to see if the password has at least one non-letter character.
{
currentPassword = newPassword1 // If all conditions are met, it sets the current password to the password entered by the user.
}
else // If there isn't a non-letter character, it informs the user and restarts the process.
{
System.out.println("The new password must have a non-letter character.");
changePassword();
}
}
else // If there is less than 6 characters, it informs the user and restarts the process.
{
System.out.println("The new password can not be less than 6 characters.");
changePassword();
}
}
else // If the new passwords don't match, it informs the user and restarts the process.
{
System.outprintln("The passwords must match.");
changePassword();
}
}

Assuming by "letter" you mean an english character in A-Z, a-z, just iterate through the string and return true if you encounter a character whose int value is outside the letter range.
public static boolean containsNonLetter(String s){
for(int i = 0; i < s.length(); i++){
int ind = (int)s.charAt(i);
if(ind < 65 || (ind > 90 && ind < 97) || ind > 122)
return true;
}
return false;
}

I am making the assumption that by letter you meant alphabets. If you use regex pattern you can have a very clean code as well you have ability to update the pattern as necessary. To learn more check Java Pattern. Here is the code.
private static final Pattern APLHA = Pattern.compile("\\p{Alpha}");
public static boolean hasLetter(String input) {
return APLHA.matcher(input).find();
}

Related

How to prevent integer input in Java?

I am trying to get my code to prevent a user input from having a number in it.
Essentially I want the code to do as follows:
ask for input
receive input
test whether or not the input contains a number(ex: 5matt vs matt)
if contains a number I want to System.out.println("Error: please do not input a number");
Heres the kicker (and why it's not a duplicate question): I can't use loops or other statements we haven't learned yet. So far the only true statements we've learned are if/else/else if statements. That means I can not use for loops, like some of the answers are suggesting. While they're great answers, and work, I'll lose points for using them.
System.out.println("Please input the first name: ");
String name1 = in.next();
System.out.println("Please input the second name: ");
String name2 = in.next();
System.out.println("Please input the third name: ");
String name3 = in.next();
name1 = name1.substring(0,1).toUpperCase() + name1.substring(1).toLowerCase();
name2 = name2.substring(0,1).toUpperCase() + name2.substring(1).toLowerCase();
name3 = name3.substring(0,1).toUpperCase() + name3.substring(1).toLowerCase();
I have this already but I can't figure out how to test if the input only contains letters.
Okay, there are many ways to deal with this. A good thing would be to use Regex (text matching stuff). But it seems that you should only use very basic comparison methods.
So, let's do something very basic and easy to understand: We iterate over every character of the input and check whether it's a digit or not.
String input = ...
// Iterate over every character
for (int i = 0; i < input.length(); i++) {
char c = s.charAt(i);
// Check whether c is a digit
if (Character.isDigit(c)) {
System.out.println("Do not use digits!");
}
}
This code is very straightforward. But it will continue checking even if a digit was found. You can prevent this using a helper-method and then returning from it:
public boolean containsDigit(String text) {
// Iterate over every character
for (int i = 0; i < input.length(); i++) {
char c = s.charAt(i);
// Check whether c is a digit
if (Character.isDigit(c)) {
return true;
}
}
// Iterated through the text, no digit found
return false;
}
And in your main program you call it this way:
String input = ...
if (containsDigit(input)) {
System.out.println("Do not use digits!");
}
Use a regular expression to filter the input
Eg
str.matches(".*\\d.*")
See this link for more info
There are several ways you could do this, among others:
Iterate over all the chars in the string and check whether any of them is a digit.
Check whether the string contains the number 1, number 2, number 3, etc.
Use a regular expression to check if the string contains a digit.
(Java Regular Expressions)
If you're allowed to define functions, you can essentially use recursion to act as a loop. Probably not what your prof is going for, but you could be just inside the requirements depending on how they're worded.
public static boolean stringHasDigit(String s) {
if (s == null) return false; //null contains no chars
else return stringHasDigit(s, 0);
}
private static boolean stringHasDigit(String s, int index) {
if (index >= s.length()) return false; //reached end of string without finding digit
else if (Character.isDigit(s.charAt(index))) return true; //Found digit
else return stringHasDigit(s, index+1);
}
Only uses if/elseif/else, Character.isDigit, and String.charAt, but recursion might be off limits as well.

Do-While loop issue, making the prompt run again -JAVA

I am attempting to make it so this program runs again if the user enters 'y'. What happens when the user does this is the program runs again, but not correctly. This is what I have so far. I know a do while loop will be best for this. Is it an error in how the variables are initialized?
String password;
boolean hasLength;
boolean hasUppercase;
boolean hasLowercase;
boolean hasDigit;
boolean hasSpecial;
String runAgain = "";
Scanner scan = new Scanner(System.in);
/******************************************************************************
* Inputs Section *
******************************************************************************/
do {
System.out.println("A password must be at least 8 character long");
System.out.println("And must contain:");
System.out.println("-At least 1 number");
System.out.println("-At least 1 uppercase letter");
System.out.println("-At least 1 special character (!##$%^&*()_+)\n");
System.out.print("Please enter your new password: ");
password = scan.nextLine();
/******************************************************************************
* Processing Section *
******************************************************************************/
System.out.print("\n");
System.out.println("Entered Password:\t" + password);
hasLength = password.length() < 8; // parameters for length
// for lower and uppercase characters
hasUppercase = !password.equals(password.toLowerCase()); //lowercase version of the password equals the password,
hasLowercase = !password.equals(password.toUpperCase()); //only if it does not contain uppercase letters.
hasDigit = password.matches(".*[0-9].*");//checks for digits
hasSpecial = !password.matches("[A-Za-z0-9]*"); //for anything not a letter in the ABC's
//prints the verdict
System.out.print("Verdict: ");
if(hasLength)
{
System.out.println("\t\tInvalid, Must have at least 8 characters");
}
if(!hasUppercase)
{
System.out.println("\t\t\tInvalid, Must have an uppercase character");
}
if(!hasLowercase)
{
System.out.println("\t\t\tInvalid, Must have a lowercase character");
}
if(!hasDigit)
{
System.out.println("\t\t\tInvalid, Must have a number");
}
if(!hasSpecial)
{
System.out.println("\t\t\tInvalid, Must have a special character");
}
System.out.print("Would you like to make another password? (Y/N) ");
runAgain = scan.next();
System.out.println("\n");
} while (runAgain.equalsIgnoreCase("Y"));
which gives this output when yes is entered to run again. It skips the prompt entirely.
Would you like to make another password? (Y/N) y
A password must be at least 8 character long
And must contain:
-At least 1 number
-At least 1 uppercase letter
-At least 1 special character (!##$%^&*()_+)
Please enter your new password:
Entered Password:
Verdict: Invalid, Must have at least 8 characters
Invalid, Must have an uppercase Character
Invalid, Must have a lowercase character
Invalid, Must have a number
Invalid, Must have a special character
Would you like to make another password? (Y/N)
You would need to read the complete line form console at runAgain = scan.next();. Just single token is being read to runAgain and the console is left with \r or Return character which will be read as next password where you do scan.nextLine(). You may change the statement to runAgain = scan.nextLine().trim();.
System.out.print("Would you like to make another password? (Y/N) ");
// runAgain = scan.next();
runAgain = scan.nextLine();
System.out.println("\n");

Palindrome code not working well in Java

This is a assignment I'm doing and it seems I can't get it to work properly.
The question is below.
A palindrome is a word or phrase that reads the same forward and
backward, ignoring blanks and considering uppercase and lowercase
versions of the same letter to be equal.for example,the following are
palindromes:
warts n straw
radar
able was I ere I saw Elba
xyzczyx
Write a program that will accept a sequence of characters terminated
by a period and will decide whether the string--without the
period---is a palindrome.You may assume that the input contains only
letters and blanks and is at most 80 characters long.Include a loop
that allows the user to check additional strings until she or he
requests that the program end.
Hint: Define a static method called isPalindrome that begins as
follows:
Precondition: The array a contains letters and blanks in
positions a[0] through a[used - 1]. Returns true if the string is a
palindrome and false otherwise.
public static boolean isPalindrome(char[] a, int used)
Your program should read the input characters into an array whose base
type is char and then call the preceding method. The int variable used
keeps track of how much of the array is used, as described in the
section entitled "Partially Filled Arrays."
This is my class code:
public class Palindrome_class
{
// instance variable
char[] characterArray;
//constructor
//#param data is a string of characters
public Palindrome_class(String data)
{
characterArray = data.toUpperCase().toCharArray();
}
//#return true if the word is a palindrome, otherwise returns false.
public boolean isPalindrome(char[] a, int used)
{
int i = 0, j = used - 1;
while (i < j)
{
if(characterArray[i] == characterArray[j])
{
i++;
j--;
}
else
{
return false;
}
}
return true;
}
}
This is my main code:
import java.util.Scanner;
public class palindromeTest
{
public static void main(String[] args)
{
int used = 0;
char[] chars = new char[80];
Scanner inputWord = new Scanner(System.in);
Scanner reply = new Scanner(System.in);
System.out.println("Enter a string characters, terminated by a period.");
String data;
String cq;
Palindrome_class word;
do
{
//input word from user.
data = inputWord.nextLine();
word = new Palindrome_class(data);
//check for palindrome.
if(word.isPalindrome(chars, used))
System.out.println(data + " is a palindrome.");
else
System.out.println(data + " is not a palindrome.");
//request to continue or quit.
System.out.println("Continue or Quit?");
cq = reply.nextLine();
}
while (cq.equalsIgnoreCase("continue"));
System.exit(0);
}
}
This is the results:
Enter a string characters, terminated by a period.
radar.
radar. is a palindrome.
Continue or Quit?
continue
use
use is a palindrome.
Continue or Quit?
continue
use.
use. is a palindrome.
Continue or Quit?
continue
apple.
apple. is a palindrome.
Continue or Quit?
Quit
Please tell me where I'm making a mistake.
You are checking whether a String is a palindrome with this call :
if(word.isPalindrome(chars, used))
However, used is 0, so your method always returns true.
You are also ignoring the instructions of your assignment. You are not doing anything with the chars array, you are not removing the period that's supposed to be at the end of the input String, your isPalindrome method is not static, etc...
U did a very little mistake.. U are sending "used" variable as 0 each time. ideally it should be length of a word.
please check it. use
used = data.length();
before sending it to the check method

Using while loop to validate password in Java

The prompt is to have a user input a password and the password must be at least 8 characters with no white spaces, must have one upper case letter, and must have one digit. It has to use a while loop. If the password conforms it should output "password ok" or otherwise say "try again"
Anyone know what to do for this?
All I can pretty much do is the scanner and user input
Use 2 boolean flags. One each for checking presence of digit, uppercase letter. Your condition could go like :
//loop start
{
if(string.charAt(i)==space){
print "not valid"
return false;
}
// check for capital letter here and set flag to true if it is found.
// check digit here and set that flag to true if found.
}//loop end
// outside the loop make these checks
if(string.length>8 && isCapitalFound && isDigitFound)
//print "valid"
return true
I made your home work for you:
boolean noWhite = false;
boolean oneUppercase = false;
boolean oneDigit = false;
Scanner scan = new Scanner(System.in);
String pass = "";
while (!noWhite || !oneUppercase || !oneDigit || pass.length() < 8) {
System.out.print("new pass: ");
pass = scan.next();
noWhite = !pass.contains(" ");
oneUppercase = !pass.equals(pass.toLowerCase());
oneDigit = pass.matches(".*\\d.*");
}
System.out.println("OK");

Java Password Checker

My problem is to create a password that contains between 6 and 10 characters and contains at least one letter and one digit, and then to have the user re-enter the password and confirm that they match.
The only issue I have is checking to see if the password has a letter or digit. I have browsed and found the same problem on the website, but I was confused about some of the methods and other things they referenced in their code since I seemed to build mine differently. I thought about using the indexOf() method to see if it returned a -1 value, but I'm not really sure where to begin.
I'm really new at java and I'm sure there is a much more efficient way to construct this, and I would love any tips.
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
//Input from user
String password;
Scanner input = new Scanner(System.in);
System.out.print("Please create your password: ");
password = input.nextLine();
//Checking password length
while( (password.length() < 6) || (password.length() > 10) )
{
System.out.print("This password must be between 6 and 10 characters. Try again: ");
password = input.nextLine();
}
//Checking to see if passwords contain digit/letter
/*Need to add code here */
//Confirming if passwords match
String password2;
System.out.print("\nPlease type your password again to confirm: ");
password2 = input.nextLine();
while( !password2.equals(password) )
{
System.out.print("Those passwords do not match. Try again: ");
password2 = input.nextLine();
}
}
}
With Regex
You should use a regular expression, to check for theese crits.
First, the code:
pwd.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,10}$")
Here's a full example:
public class HelloWorld{
public static void main(String []args){
String password = "aA2";
String regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,10}$";
System.out.println(password.matches(regexp));
password = "12345678";
System.out.println(password.matches(regexp));
password = "aA345678";
System.out.println(password.matches(regexp));
}
}
gives the following output:
false
false
true
The regexp matches any string, that conatins at least upper case, one lower case letter and one digit, and 6 - 10 character long.
You can find more examples of theese here. And some info about the regexps on the Wikipedia. A very good tutorial about regexps and Java can be found on Vogella. (It's a very good site, with very good tutorials, I think!) And, a handy tool to display what a regexp matches: http://www.regexper.com/
In case of the previous example, it gives you a very visually output.
Without Regexs
So, if you cannot use Regulax Expressions, I would create a function, which returns true, if the password is OK, false in any other case. Here's a small example for this function:
public static boolean passwordOk(String password){
if (password == null) return false;
if (password.length() < 6 || password.length() > 10) return false;
boolean containsUpperCase = false;
boolean containsLowerCase = false;
boolean containsDigit = false;
for(char ch: password.toCharArray()){
if(Character.isUpperCase(ch)) containsUpperCase = true;
if(Character.isLowerCase(ch)) containsLowerCase = true;
if(Character.isDigit(ch)) containsDigit = true;
}
return containsUpperCase && containsLowerCase && containsDigit;
}
The main idea thing in this solution, is a for-each loop. I create a character array from the String, and loop over the elements of it. If the current character is a digit, or uppercase, or lowercase, I set a flag, to sign, that one of the statements are true. At the beginning, all of the statements are false, and at the end I'll return the result of their sum.
In the first two lines I check, if the argument isn't null, and if it has the right length.
I hope, that after this you'll be able to solve your homework! You can call this function even with null pointers, so I would create a while loop, to run while this function do not returns true.
If it's hopeless, to solve this problem, here's the full code.
Believe me, it'll be more useful, if you try to solve this by your own, first!
You can use something like this...
if( password.matches(".*[a-zA-Z]+.*")){
System.out.println( "Has characters ");
} else {
System.out.println("Ok");
}
This is to check if the password contains a letter
Similarly you can use the regular expression ".*[0-9]+.*" to check if the password contains a digit.

Categories

Resources