Checking for digits - java

I'm trying to figure out this problem. The directions are set hasDigit to true when a three character passCode from a scanner contains a digit.
Code below
import java.util.Scanner;
public class CheckingPasscodes {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
boolean hasDigit;
String passCode;
hasDigit = false;
passCode = scnr.next();
hasDigit = Character.isDigit(passCode);
if (hasDigit) {
System.out.println("Has a digit.");
}
else {
System.out.println("Has no digit.");
}
}
}
I've entered in the line
hasDigit = Character.isDigit(passCode);
My logic is that character.isDigit is checking the passCode from the scanner, but I keep getting an error.
I've also tried:
hasDigit = Character.isDigit(0);
and the first test passes, but not the other. From this I assumed that I would have to enter in the string so it would test for anything, not just the character at position 0.
Thanks for the help.

import java.util.Scanner;
public class CheckingPasscodes {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
boolean hasDigit;
String passCode;
hasDigit = false;
passCode = scnr.next();
if ((Character.isDigit(passCode.charAt(0))) || (Character.isDigit(passCode.charAt(1))) || (Character.isDigit(passCode.charAt(2)))) {
hasDigit = true;
}
if (hasDigit) {
System.out.println("Has a digit.");
}
else {
System.out.println("Has no digit.");
}
}
}

for(int i = 0 ;i <passCode.length();i++) {
hasDigit = Character.isDigit(passCode.charAt(i));
if (hasDigit) {
System.out.println("Has a digit.");
break;
}
}
if(!hasDigit) {
System.out.println("Has no digit.");
}
Pity that the answer was revealed but if you are going to spoil the learning process at least try giving the right code :/

isDigit() function of Character class excepts either one character or an integer. It does not excepts string , that's why you are getting error. You can modify your code to -
hasDigit = false;
passCode = scnr.next();
for(int i = 0 ;i <passCode.length();i++) {
hasDigit = Character.isDigit(passCode.charAt(i));
if(hasDigit)
break;
}
if (hasDigit) {
System.out.println("Has a digit.");
}
else {
System.out.println("Has no digit.");
}
this will give you required result.

Related

How do I make sure that the input is not null and that only one character is being entered?

public static boolean correctchar(char b) {
Scanner scan = new Scanner(System.in);
b = scan.next().charAt(0);
if (Character.toString(b).matches("^[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
I have this method that checks whether the input is a letter in the alphabet or not, but I want to make sure that the input from the user is not null and that the user only enters one letter. For example "A" or "a" is a correct char, the problem is if I enter "Abcdef" then it is still true as the first letter is still a valid char. I want to make it so that the user can only enter one char, I think I've done that by using the scanner and charAt(0) but is there a more efficient way to do it, and I'm also not sure how to make it so that the input isn't null.
I've revised your code to do what you wanted:
public static boolean correctchar(char b) {
Scanner scan = new Scanner(System.in);
String input = scan.next();
// This checks if the input is null, is empty (i.e., "") or is bigger than one character
// If any of these conditions are fulfilled, then we return false.
if (input == null || input.length() != 1) {
return false;
}
b = input.charAt(0);
if (Character.toString(b).matches("[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
EDIT
Without scanner (see comments):
public static boolean correctchar(char b, String input) {
// This checks if the input is null, is empty (i.e., "") or is bigger than one character
// If any of these conditions are fulfilled, then we return false.
if (input == null || input.length() != 1) {
return false;
}
b = input.charAt(0);
if (Character.toString(b).matches("[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
I made couple of changes :
If invalid input ask user to enter again.
Make sure to close the scanner scan.close()
Scanner scan = new Scanner(System.in);
System.out.println("Please enter only one character : ");
String input = scan.next();
while (null == input || input.isEmpty() || input.length() > 1) {
System.out.println("Invaid Input, Please enter only one character : ");
input = scan.next();
}
scan.close();
if (Character.toString(input.charAt(0)).matches("^[a-zA-Z]")) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
public static boolean correctChar() {
try (Scanner scan = new Scanner(System.in)) {
String input = null;
do {
input = scan.next();
if (input != null && input.length() == 1) {
boolean isCorrect = input.matches("[a-zA-Z]");
System.out.println(isCorrect ? "True" : "False");
return isCorrect;
} else {
System.out.println("Insert only one character");
}
} while (true);
}
}

Is there anyway to shorten this Java code by validating name and weight using only one do...while?

Is there any way to validate name(String) and weight(double) in only one do while?
How to add optional regex such as [./ ] besides [a-zA-Z]+ ?
do {
System.out.print("Name: ");
name = input.nextLine();
if (Pattern.matches("[a-zA-Z]+", name)) {
isValid = true;
} else {
System.out.println("Invalid input\nPlease try again\n");
isValid = false;
}
} while (!(isValid));
do {
System.out.print("Height(cm): ");
input.nextLine();
if (input.hasNextDouble()) {
height = input.nextDouble();
if (height > 5 && height <= 500) {
isValid = true;
} else {
System.out.println("Invalid input\nPlease try again\n");
isValid = false;
}
} else {
System.out.println("Invalid input\nPlease try again\n");
isValid = false;
}
} while (!(isValid));
You can add the optional regular expression [./ ] into the same pattern separated by |. Validation in a single do-while can be performed like this:
import java.util.regex.*;
import java.util.*;
public class StackOverflow
{
public static void main(String[] args)
{
Boolean isNameValid = false, isHeightValid = false;
String name = null; double height = 0;
Scanner input = new Scanner(System.in);
Pattern pattern = Pattern.compile("[a-zA-Z]+|[./ ]");
do
{
if(!isNameValid)
{
System.out.print("Name: ");
name = input.nextLine();
Matcher match = pattern.matcher(name);
if (match.find())
isNameValid = true;
else
{
System.out.println("Invalid input\nPlease try again\n");
isNameValid = false;
}
}
if(isNameValid && !isHeightValid)
{
System.out.print("Height(cm): ");
if (input.hasNextDouble())
{
height = input.nextDouble();
if (height > 5 && height <= 500)
isHeightValid = true;
else
{
System.out.println("Invalid input\nPlease try again\n");
isHeightValid = false;
}
}
else
{
System.out.println("Invalid input\nPlease try again\n");
isHeightValid = false;
}
}
}while(!(isNameValid)||!(isHeightValid));
input.close();
}
}
You can do something like this:
Boolean validName = false, validWeight = false;
do {
if(!validName) {
//get and validate weight
// when found the correct name; set validName to true
}
if(validName && !validWeight) {
//get and validate weight
}
}while(validName && validWeight);
If there are more than two such validations you can wrap each read-validate in a function.

password validation using boolean

I have to write a code that check if a password is valid.
The problem is when the password pass every condition I don't get any answer if it's.
Right here you can see my code; I think I need to add something in my main function but I don't know what.
Is the else if statement not necessary?
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a password : ");
String passwordhere = in.nextLine();
List<String> errorList = new ArrayList<String>();
while (!isValid(passwordhere, errorList)) {
System.out.println("The password entered here is invalid");
for (String error : errorList) {
System.out.println(error);
}
System.out.print("Please enter a given password : ");
passwordhere = in.nextLine();
}
}
public static boolean isValid(String passwordhere, List<String> errorList) {
Pattern specailCharPatten = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Pattern UpperCasePatten = Pattern.compile("[A-Z ]");
Pattern lowerCasePatten = Pattern.compile("[a-z ]");
Pattern digitCasePatten = Pattern.compile("[0-9 ]");
errorList.clear();
boolean flag=true;
if (passwordhere.length() < 8) {
errorList.add("Password lenght must have alleast 8 character !!");
flag=false;
}
if (!specailCharPatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one specail character !");
flag=false;
}
if (!UpperCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one uppercase character !");
flag=false;
}
if (!lowerCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one lowercase character !");
flag=false;
}
if (!digitCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one digit character !");
flag=false;
}
else if(digitCasePatten.matcher(passwordhere).find()&&passwordhere.length() < 8&&
specailCharPatten.matcher(passwordhere).find()&&lowerCasePatten.matcher(passwordhere).find()&&
UpperCasePatten.matcher(passwordhere).find()){
System.out.println("the pass is right");
flag=true;
}
return flag;
}
}
while (true) {
if (!isValid(passwordhere, errorList)) {
System.out.println("The password entered here is invalid");
for (String error : errorList) {
System.out.println(error);
}
System.out.print("Please enter a given password : ");
passwordhere = in.nextLine();
}
else {
System.out.println("Password is valid!");
break;
}
}
or change just your method isValid like this :
public static boolean isValid(String passwordhere, List<String> errorList) {
Pattern specailCharPatten = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Pattern UpperCasePatten = Pattern.compile("[A-Z ]");
Pattern lowerCasePatten = Pattern.compile("[a-z ]");
Pattern digitCasePatten = Pattern.compile("[0-9 ]");
errorList.clear();
boolean flag=true;
if (passwordhere.length() < 8) {
errorList.add("Password lenght must have alleast 8 character !!");
flag=false;
}
if (!specailCharPatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one specail character !");
flag=false;
}
if (!UpperCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one uppercase character !");
flag=false;
}
if (!lowerCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one lowercase character !");
flag=false;
}
if (!digitCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one digit character !");
flag=false;
}
if(flag) System.out.println("the pass is right");
return flag;
}
else if( ... &&passwordhere.length() < 8 ...) <-- sth wrong here.
But I think u don't need else if. After checking all, it's true or false.
So just
if (flag){
System.out.println("the pass is right");
}

Java password checker with strings

Been fighting with this for awhile, still new to java and really struggling with this assignment. We're meant to make a password checker assignment that checks if 2 entered passwords are the same. Then also check them against some "requirements" such as password length of at least 8 characters, one special character, one upper and one lower case, no repeating characters more than 3 times consecutively, (ie "aaa").
Any input or criticism is very much appreciated and thank you in advance.
import java.util.Scanner;
/**
*
* #author Jonot
*/
public class Passwords {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Asks and records users inputted passwords
Scanner input = new Scanner(System.in);
System.out.println("Please enter your password");
String password = input.nextLine();
System.out.println("Please re-enter your password");
String passwordCheck = input.nextLine();
//boolean to check if the inputted passwords meets requirements set below
boolean check;
check = isConfirmed(password);
while (!password.equals(passwordCheck) || (!check)) {
System.out.println("The password you entered is invalid");
System.out.println("Please try again");
password = input.nextLine();
System.out.println("please re-enter");
passwordCheck = input.nextLine();
check = isConfirmed(password);
//String password = input.nextLine();
//check = isConfirmed(password);
//if passwords meets boolean requirements,
if (isConfirmed(password)) {
//this will print out. Doesn't work right now.
System.out.println("password is valid");
} else {
}
}
}
//Boolean variables and they're set requirements. Do not work right now.
//Not sure why.
public static boolean isConfirmed(String password) {
Boolean leastOneUpperCase = false;
Boolean leastOneLowerCase = false;
Boolean leastOneDigit = false;
Boolean oneSpecialCharacter = false;
if (password.length() < 8) {
return false;
}
for (int i = 0; i < password.length(); i++) {
if (Character.isUpperCase(password.charAt {i
));
{
leastOneUpperCase = true;
}
else if (Character.isLowerCase(password.charAt(i)));
{
leastOneLowerCase = true;
}
else if (Character.isDigit(password.charAt(i)));
{
leastOneDigit = true;
}
}
return (leastOneUpperCase && leastOneLowerCase && leastOneDigit);
}
return false;
}
There was one primary problem, in the isConfirmed method. The return statement with the variables in it was inside the loop that checked each character. So, the return statement was executed after the first character was checked and therefore always returned false, since two out of the three booleans would still be false.
Also, looked like some semicolons were out of place in your charAt checks. Not sure if that's a formatting error introduced during your post. Finally, I thought the code would be more readable by pulling the current character being checked into a variable and using that instead of calling charAt a bunch of times.
Here's the revised code:
import java.util.Scanner;
/**
*
* #author Jonot
*/
public class Passwords {
/**
* #param args the command line arguments
*/
public static final void main(String[] args) {
//Asks and records users inputted passwords
Scanner input = new Scanner(System.in);
System.out.println("Please enter your password");
String password = input.nextLine();
System.out.println("Please re-enter your password");
String passwordCheck = input.nextLine();
//boolean to check if the inputted passwords meets requirements set below
boolean check;
check = isConfirmed(password);
while (!password.equals(passwordCheck) || (!check)) {
System.out.println("The password you entered is invalid");
System.out.println("Please try again");
password = input.nextLine();
System.out.println("please re-enter");
passwordCheck = input.nextLine();
check = isConfirmed(password);
//String password = input.nextLine();
//check = isConfirmed(password);
//if passwords meets boolean requirements,
if (isConfirmed(password)) {
//this will print out. Doesn't work right now.
System.out.println("password is valid");
} else {
}
}
}
//Boolean variables and they're set requirements. Do not work right now.
//Not sure why.
public static boolean isConfirmed(String password) {
Boolean leastOneUpperCase = false;
Boolean leastOneLowerCase = false;
Boolean leastOneDigit = false;
Boolean oneSpecialCharacter = false;
if (password.length() < 8) {
return false;
}
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (Character.isUpperCase(c))
{
leastOneUpperCase = true;
}
else if (Character.isLowerCase(c))
{
leastOneLowerCase = true;
}
else if (Character.isDigit(c))
{
leastOneDigit = true;
}
System.out.println("password is valid");
} else {
}
}
}
//Boolean variables and they're set requirements. Do not work right now.
//Not sure why.
public static boolean isConfirmed(String password) {
Boolean leastOneUpperCase = false;
Boolean leastOneLowerCase = false;
Boolean leastOneDigit = false;
Boolean oneSpecialCharacter = false;
if (password.length() < 8) {
return false;
}
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (Character.isUpperCase(c))
{
leastOneUpperCase = true;
}
else if (Character.isLowerCase(c))
{
leastOneLowerCase = true;
}
else if (Character.isDigit(c))
{
leastOneDigit = true;
}
}
return (leastOneUpperCase && leastOneLowerCase && leastOneDigit);
}
}

Recursive Palindrome

First of all I am not telling anyone to "do my homework." I just need a little help on how to keep repeating a process. This is the program I did below and it has a tester class with it.
The class:
class RecursivePalindrome {
public static boolean isPal(String s)
{
if(s.length() == 0 || s.length() == 1)
return true;
if(s.charAt(0) == s.charAt(s.length()-1))
return isPal(s.substring(1, s.length()-1));
return false;
}
}
Then the tester class which has the main method:
public class RecursivePalindromeTester {
public static void main(String[] args)
{
RecursivePalindrome Pal = new RecursivePalindrome ();
boolean quit = true;
Scanner in = new Scanner(System.in);
System.out.print("Enter a word to test whether it is a palindrome or not(press quit to end.): ");
String x = in.nextLine();
while(quit) {
boolean itsPal = Pal.isPal(x);
if(itsPal == true){
System.out.println(x + " is a palindrome.");
quit = false;
}
else if (x.equals("quit")) {
quit = false;
}
else {
quit = false;
System.out.println(x + " is not a palindrome.");
}
}
}
}
This program find if the letter is Palindrome or not. I got all the calculations and stuff in but what do i do to keep asking the user for input and every time the user inputs it says if it is a Palindrome word or not.
Just move the lines asking for user input and reading it:
System.out.print("Enter a word to test whether it is a palindrome or not(press quit to end.): ");
String x = in.nextLine();
...into your loop, e.g., just after the
while (quit) {
...line.
Side note: quit seems like an odd name for a boolean which, when true, means you keep going. :-)
Simply wrap with another while loop.
Look into the continue and break statements. They are very helpful for loops, which is what you're looking for information on here.
public class RecursivePalindromeTester {
public static void main(String[] args) {
RecursivePalindrome Pal = new RecursivePalindrome ();
Scanner in = new Scanner(System.in);
while(true){
System.out.print("Enter a word to test whether it is a palindrome or not(press quit to end.): ");
String x = in.nextLine();
boolean itsPal = Pal.isPal(x);
if(itsPal == true){
System.out.println(x + " is a palindrome.");
} else if (x.equals("quit")) {
break;
} else {
System.out.println(x + " is not a palindrome.");
}
}
}
}

Categories

Resources