Validating e-mail username and password using try/catch block - java

I'm trying to write a code that validates an email as a username and a password that has at least one uppercase, one lowercase, and one special character. When I run the program, I'm getting "Successfully signed up." no matter what I input. I believe my error is in my try/catch block.
import java.util.Scanner;
public class UserSignUp {
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
String username;
String password;
try {
System.out.print("Enter your username: ");
username = input1.nextLine();
System.out.print("Enter your password: ");
password = input2.nextLine();
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println("Successfully signed up.");
}
public static void validateUsername(String username) throws IllegalArgumentException {
String pattern = ".+#.+\\.com";
if (username.matches(pattern)) {
throw new IllegalArgumentException("Invalid username.");
}
}
public static void validatePassword(String password) throws IllegalArgumentException {
boolean isUppercase = false;
boolean isLowercase = false;
boolean isDigit = false;
boolean hasSpecialCharacter = false;
char ch = 0;
for (int i = 0; i < password.length(); i++) {
ch = password.charAt(i);
if (Character.isUpperCase(ch)) {
isUppercase = true;
} else {
throw new IllegalArgumentException("Password must contain an uppercase letter.");
}
if (Character.isLowerCase(ch)) {
isLowercase = true;
} else {
throw new IllegalArgumentException("Password must contain a lowercase letter.");
}
if (Character.isDigit(ch)) {
isDigit = true;
} else {
throw new IllegalArgumentException("Password must contain a digit.");
}
if (!Character.isDigit(password.charAt(ch)) && !Character.isLetter(password.charAt(ch))) {
hasSpecialCharacter = true;
} else {
throw new IllegalArgumentException("Password must contain a special character.");
}
}
}
}

Here is my solution to it, the explanation is already embedded:
import java.util.Scanner;
public class UserSignUp {
public static void main(String[] args) {
// No need for two scanners, one scanner can accept multiple (also
// multiple-lined) inputs.
Scanner in = new Scanner(System.in);
try {
// Put validation inside the try block.
// Regarding there are no other use of the variables, it is unnecessary to give
// the two variables "Method Level Scope" instead of "Block Scope".
System.out.print("Enter your username: ");
String username = in.nextLine();
validateUsername(username);
System.out.print("Enter your password: ");
String password = in.nextLine();
validatePassword(password);
// Put the println() inside the try block.
System.out.println("Successfully signed up.");
} catch (IllegalArgumentException e) {
System.out.println(e);
}
}
public static void validateUsername(String username) throws IllegalArgumentException {
String pattern = ".+#.+\\.com";
// If not matches the pattern,
if (!username.matches(pattern)) {
throw new IllegalArgumentException("Invalid username.");
}
}
public static void validatePassword(String password) throws IllegalArgumentException {
boolean isUppercase = false;
boolean isLowercase = false;
boolean isDigit = false;
boolean hasSpecialCharacter = false;
char ch = '\0';
for (int i = 0; i < password.length(); i++) {
ch = password.charAt(i);
if (Character.isUpperCase(ch))
isUppercase = true;
if (Character.isLowerCase(ch))
isLowercase = true;
if (Character.isDigit(ch))
isDigit = true;
// ch is already defined as a character.
if (!Character.isDigit(ch) && !Character.isLetter(ch))
hasSpecialCharacter = true;
}
// Ask for the constraints after read through all characters.
if (isUppercase != true)
throw new IllegalArgumentException("Password must contain an uppercase letter.");
else if (isLowercase != true)
// Fix the error message of lower-case letters.
throw new IllegalArgumentException("Password must contain a lowercase letter.");
else if (isDigit != true)
throw new IllegalArgumentException("Password must contain a digit.");
else if (hasSpecialCharacter != true)
throw new IllegalArgumentException("Password must contain a special character.");
}
}
Hope this answer helps and please leave this question as it is as someone might need it, unless there is important changes.

Related

How could I get my program to check if a word is a palindrome irrespective of the case entered by the user

import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
isPailindrome(ori);
if (isPailindrome(ori))
System.out.println(ori + "is a Pailindrome");
else
System.out.println(ori + "is NOT a Pailindrome");
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}
The code works perfectly I'm just confused how I will get it to work irrespective of the case
inputted by the user. For example aBba is a palindrome but It says it's not in the code I've done. I
would like any help if possible thanks.
You can convert all of the letters to lowerCase before you start the processing.
You can write your own function or use toLowerCase() String function.
import java.util.Scanner;
public class Pailindrome {
public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("Please enter a word");
String ori = sc1.nextLine();
ori = ori.toLowerCase();
isPailindrome(ori);
if (isPailindrome(ori))
}
System.out.println(ori + "is a Pailindrome");
} else {
System.out.println(ori + "is NOT a Pailindrome");
}
}
public static boolean isPailindrome(String ori) {
int i = 0;
int j = ori.length() - 1;
while (i < j) {
if (ori.charAt(i) != ori.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
Take the input and call toUpper(); that way when you check to see if it is a palindrome, all of the characters are uppercase.
String ori = scr.nextLint();
if(isPalindrome(ori.toUpperCase()))
//do something
Convert all the cases to lowercase/uppercase before checking the palindrome
isPailindrome(ori.toLowerCase());
Zoom in from both ends and adjust the case as required.
public static boolean isPalindrome(String str) {
int len = str.length();
for (int i = 0; i < len >>1; i++) {
if (Character.toLowerCase(str.charAt(i)) !=
Character.toLowerCase(str.charAt(len - i - 1))) {
return false;
}
}
return true;
}

Password Check Program - checking capitals, lowercase letters, digit and special character

I have an assignment that requires me to create a password checking program.
The password must be at least 8 characters, contain both capital and lower case letters, a digit and a special character.
I believe I am close to solving this problem but my skills are still developing and I've hit a wall.
package project1;
/**
*
* #author danechristian
*/
import java.util.*;
public class Project1
{
static Scanner console = new Scanner(System.in);
static final String SPECIAL_CHARACTERS = "!,#,$,%,^,&,*,|";
static String password;
public static void main(String[] args)
{
System.out.println("Create a password: ");
password = console.next();
if (validPassword(password))
{
System.out.println("Password Saved");
}
else
{
System.out.println("Invalid Passowrd. Password "
+ "must contain atleast 1 capital letter"
+ "1 lower case letter, 1 digit, 1"
+ "special character (!#$%^&*|) and "
+ "be atleast 8 characters long");
}
}
public static boolean validPassword(String password)
{
boolean upCase = false;
boolean loCase = false;
boolean isDigit = false;
boolean spChar = false;
if (password.length() >= 8)
{
for (int i = 0; i < password.length() - 1; i++)
{
if (Character.isUpperCase(password.charAt(i)))
{
upCase = true;
}
if (Character.isLowerCase(password.charAt(i)))
{
loCase = true;
}
if (Character.isDigit(password.charAt(i)))
{
isDigit = true;
}
if (SPECIAL_CHARACTERS.contains(password))
{
spChar = true;
}
}
}
return (upCase && loCase && isDigit && spChar);
}
}
In order to check have something like this:
public static boolean validPassword(String password){
boolean upCase = false;
boolean loCase = false;
boolean isDigit = false;
boolean spChar = false;
if (password.length()>7){
if (password.matches(".+[A-Z].+")){
upCase = true;
}
if (password.matches(".+[a-z].+")){
loCase = true;
}
if (password.matches(".+[1-9].+")){
isDigit = true;
}
if (SPECIAL_CHARACTERS.contains(password)){
spChar = true;
}
}
return (upCase && loCase && isDigit && spChar);
}
solved by changing
if (SPECIAL_CHARACTERS.contains(password)){
spChar = true;
to
if (SPECIAL_CHARACTERS.contains(password.substring(i,i+1))){
spChar = true;
this checks for the string within the string.
also, I removed the "- 1" from my for statement so that the bounds were corrects. also removed the commas from the SPECIAL_CHARACTERS constant.
the program now runs without issue, thanks for the advice everyone.

Java code for guessing game not printing anything

So I have a Computer Science course at school in which we learn Java. We were assigned to do a simple text based recreation of the guessing game. I got it done until this point, and I cannot seem to find where I messed up because there is nothing printed when I run the core.
This is the code:
public class GuessGame
{
public static void main(String[] args)
{
new GuessGame();
}
public GuessGame ()
{
char end = 'y';
while (end!='y')
{
System.out.println ("Welcome to the Guessing Game!");
System.out.println ("\nThe computer has picked a number");
System.out.println ("between 1 and 100. Try to guess it.");
int num = (int)(Math.random()*(100-1)+1);
int guess = IBIO.inputInt ("Guess the number: ");
if (guess==num)
System.out.println ("You got it!");
else if (guess>num)
System.out.println ("That is too high.");
else
System.out.println ("That is too low.");
end = IBIO.inputChar ("Exit game? (y/n)");
}
}
}
By the way, IBIO is a class provided by my IB program that we use to make Input/Output statements.
This is IBIO.java:
public class IBIO
{
static void output (String info)
{
System.out.println (info);
}
static void output (char info)
{
System.out.println (info);
}
static void output (byte info)
{
System.out.println (info);
}
static void output (int info)
{
System.out.println (info);
}
static void output (long info)
{
System.out.println (info);
}
static void output (double info)
{
System.out.println (info);
}
static void output (boolean info)
{
System.out.println (info);
}
static String input (String prompt)
{
String inputLine = "";
System.out.print (prompt);
try
{
inputLine = (new java.io.BufferedReader (new java.io.InputStreamReader (System.in))).readLine ();
}
catch (Exception e)
{
String err = e.toString ();
System.out.println (err);
inputLine = "";
}
return inputLine;
}
static String inputString (String prompt)
{
return input (prompt);
}
static String input ()
{
return input ("");
}
static int inputInt ()
{
return inputInt ("");
}
static double inputDouble ()
{
return inputDouble ("");
}
static char inputChar (String prompt)
{
char result = (char) 0;
try
{
result = input (prompt).charAt (0);
}
catch (Exception e)
{
result = (char) 0;
}
return result;
}
static byte inputByte (String prompt)
{
byte result = 0;
try
{
result = Byte.valueOf (input (prompt).trim ()).byteValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static int inputInt (String prompt)
{
int result = 0;
try
{
result = Integer.valueOf (input (prompt).trim ()).intValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static long inputLong (String prompt)
{
long result = 0;
try
{
result = Long.valueOf (input (prompt).trim ()).longValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static double inputDouble (String prompt)
{
double result = 0;
try
{
result = Double.valueOf (input (prompt).trim ()).doubleValue ();
}
catch (Exception e)
{
result = 0;
}
return result;
}
static boolean inputBoolean (String prompt)
{
boolean result = false;
try
{
result = Boolean.valueOf (input (prompt).trim ()).booleanValue ();
}
catch (Exception e)
{
result = false;
}
return result;
}
}
Sorry for the lengthy question. Im new to Java.
The computer is doing exactly what you told it to. When GuessGame's constructor runs:
Declare end as a char local variable and initialise it to contain 'y':
char end = 'y';
Run the loop body while end does not contain 'y':
while (end!='y')
(since end does contain 'y' it does not run the loop body; it skips to the code after the loop).
The problem is that you will never enter the initial loop
char end = 'y';
while (end!='y')
You instantiate end to y, then enter only if end is not y which will always be false, hence never enter the loop.
Simply change the default value of end
char end = 'n';
Also, you don't have to cast the value 0 in your IBIO class
result = (char) 0;
You can simply do result = 0 and it will take the ASCII value.
I would also declare num and guess outside of the loop to avoid re-declaring them each time, as you did for end.
Finally, instead of declaring 7 output method with different paremeter type which simply do a System.out.println of the received parameter I would directly call System.out.println(value).
I would apply the same logic for all other methods that only call one method with the received parameter.
These two lines clearly contradict each other, the while loop will never execute. Initialize end to be a different value.
char end = 'y';
while (end!='y')
You initialize the variable char end with value 'y'.
char end = 'y';
Then the condition for your loop is
while (end!='y')
This condition is never fulfilled, that's why it's out of the loop. Change the initial value of the variable end.

Scanner returning no line found

I am getting a "No line found" exception when I run this. This is the only method in my project that gives me this error. Every other method uses the same code and parameters, but none of them encounter this error.
The method in question is findLargestPalindrome()
Exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at cs1410.TestClass.findLongestPalindrome(TestClass.java:51)
at cs1410.TestClass.main(TestClass.java:12)
import java.util.Scanner;
import java.util.StringTokenizer;
public class TestClass
{
static Scanner test = new Scanner("Hello world! This is my program.");
public static void main(String[] args)
{
System.out.println(findLongestPalindrome(test));
}
public static boolean isPalindrome(String s)
{
if(s.length() == 0)
{
return false;
}
int stringLength = s.length() -1;
if(stringLength == 0)
{
return false;
}
for(int i = 0; i < stringLength; i++)
{
if(s.charAt(i) == s.charAt(stringLength))
{
stringLength--;
}
else
{
return false;
}
}
return true;
}
public static String findLongestPalindrome(Scanner s)
{
int pLength = 0;
String largestPalindrome = "";
String currentToken;
if(s.nextLine().length() > 0)
{
String input = s.nextLine();
StringTokenizer inputTokens = new StringTokenizer(input);
while(inputTokens.hasMoreTokens())
{
currentToken = inputTokens.nextToken();
if(isPalindrome(currentToken) == true)
{
if(currentToken.length() > pLength)
{
pLength = currentToken.length();
largestPalindrome = currentToken;
}
}
}
}
else
{
return null;
}
return largestPalindrome;
}
}
When you access the Scanner in findLongestPalindrom() you only have one line in the Scanner ("Hello world! This is my program.") and you are trying to read two lines (you discard the first line),
if(s.nextLine().length() > 0) // <-- reads the line and advances
{
String input = s.nextLine(); // <-- there isn't another line.
should be something like
String input = s.nextLine();
if (!input.isEmpty()) {
// ...
or
String input = s.nextLine();
if (input.length() > 0) {
// ...
Every time you call Scanner.nextLine() you consume the line.

Using the same values in separate if statements in java

I am working on a problem where I have a menu option 1. to shuffle the word, 2 to take the shuffle word and try to fix it by changing the array index numbers.
I did this part if (input==1) shuffle the word.
I now have to take that the same shuffle word in in if (input==2) section and try to fix it. Can anybody guide me how can I use the same values in this block if(input==1)?
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Project2 {
public static void main(String[] args) {
while (true) {
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan = new Scanner(System.in);
input = scan.nextInt();
String team;
String mix_word;
char orig_team[];
char mix_team[];
boolean Result;
// System.out.println(input);
if (input == 1) {
team = orig();
System.out.println(team);
mix_word = mix(team);
System.out.println(mix_word);
orig_team = team.toCharArray();
mix_team = mix_word.toCharArray();
int arg_length = mix_team.length;
}
if (input == 2) {
}
if (input == 3) {
break;
}
if (input > 3 || input <= 0) {
System.out.println("input accurate numbers 1 or 2 or 3");
}
}
}
static String mix(String Team) {
String word = shuffle(Team);
return word;
}
static String shuffle(String input) {
List<Character> characters = new ArrayList<Character>();
for (char c : input.toCharArray()) {
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while (characters.size() != 0) {
int randPicker = (int) (Math.random() * characters.size());
output.append(characters.remove(randPicker));
}
return output.toString();
}
static String orig()
{
String[] lines = new String[1000];// Enough lines.
int counter = 0;
try {
File file = new File("input.txt");// The path of the File
FileReader fileReader1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(fileReader1);
boolean flag = true;
while (true) {
try {
lines[counter] = buffer.readLine();// Store a line in the
// array.
if (lines[counter] == null) {// If there isn't any more
// lines.
buffer.close();
fileReader1.close();
break;// Stop reading and close the readers.
}
counter++;
} catch (Exception ex) {
break;
}
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
} catch (IOException ex) {
System.out.println("Exception ocurred.");
}
int pick;
Random rand = new Random();
pick = rand.nextInt(counter) + 0;
return (lines[pick]);
}
}
In every loop cycle (which handles a single user input) you declare your variables, so their scope (the access range) is limited to that cycle.
If you declare your variables outside the while-loop, their scope will stretch over the whole loop (until the end of the method):
public static void main(String[] args) {
String team = "";
String mix_word = "";
char orig_team[] = null;
char mix_team[] = null;
boolean Result = false;
while (true) {
// ** your usual input handling here **
}
}
Also be sure to initialize them (e.g. with a default value), or else the program will not compile.
Another way would be to create member- or class-variables, which would have the advantage of automatic initialization and a larger scope.
This is a rather pathological use case of the switch statement but you can take advantage of the drop-through and do the following:
switch(input) {
case 1:
team = orig();
System.out.println(team);
mix_word = mix(team);
System.out.println(mix_word);
orig_team = team.toCharArray();
mix_team = mix_word.toCharArray();
arg_length = mix_team.length;
// No break; here!
case 2:
// do the rest of your thing as if it were case 2
break;
case 3:
break;
default:
System.out.println("input accurate numbers 1 or 2 or 3");
}

Categories