Validating user input with a loop - java

Alrighty, I'm currently trying to make a program that takes input, in the form of a email address, from the user and checks to see if it has a '#' in it. I want to use a loop to steps through the whole string that the user entered, and checks each character for the '#'. I'm a little lost as to how to get started.
What I did, was use a for loop to iterate through the whole string that the user entered. Then I used a do/while loop to execute a certain line of code until the user entered a valid email. However, it seems to always be valid no matter if it has a '#' or not. I also want to check if it only contains 1 '#' in it. I'm a little lost as you can see, but any help would be appreciated!
import java.util.Scanner;
class Test
{
public static void main(String args[])
{
System.out.print("Enter an email address ");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
valid c = new valid(input);
}
}
class valid
{
String scan2;
char amper = '#';
int i;
valid(String scan1)
{
scan2 = scan1;
for (i = scan2.length() - 1 ; i <= 0; i--)
do
{
System.out.print("That input is invalid");
} while(scan2.indexOf(i) != amper);
System.out.println("That input is valid");
}
}

Since you have to use a loop, I would recommend charAt. It gives you the character at a given index in a string:
boolean found = false;
//where string is the input that you are scanning to find an email address
for (int i = 0; i < string.length; i++){
if (string.charAt(i) == '#'){
found = true;
break;
}
}
if (found){
System.out.println("Found the # character!");
}

Hope it helps you
Loop the each character in the loop.
Check for '#' character
String email = "test#gmal.com";
boolean valid = false;
for (int i=0;i<=email.length();i++) {
if (email.charAt(i)== '#') {
valid = true;
break;
}
}
if (valid) {
System.out.println("This is valid email Id");
} else {
System.out.println("This is an Invalid email Id");
}

Others have already made some helpful comments, but here a few other things I have noticed:
Did you mean to have no "{} after the for statement? Not having that { } can change the program.
In the for statement, did you want it to be i <= 0 or i >= 0? If i starts out being the length of the input string and the test in the for statement is i <= 0, it will never be true unless the input is zero length.
Why do you have a scan1 and a scan2 String?
You may want to consider removing your search logic from the constructor.

I recommend using charAt() method in this case. Here is my code.
import java.util.Scanner;
public class EmailAddr {
private String emailAddress;
public EmailAddr(String emailAddress){
this.emailAddress = emailAddress;
}
public boolean isValid(){
boolean isValid = false;
int nAtSign = 0;
for (int i = 0; i < emailAddress.length(); i++){
if(emailAddress.charAt(i) == '#')
nAtSign++;
}
if(nAtSign == 1)
isValid = true;
return isValid;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your email address: ");
EmailAddr emailTest = new EmailAddr(sc.nextLine());
sc.close();
if(emailTest.isValid()){
System.out.println("The email address is VALID!");
} else {
System.out.println("The email address is INVALID!");
}
}
}

Javadoc concerning indexOf:
the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.
For example:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your E-Mail:");
String line;
do {
line = sc.nextLine();
}
while(line.indexOf('#') == -1);

Why dont you try with regular expressions ??
public class EmailValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean flag;
do{
String pattern="[a-zA-Z]*#[a-zA-Z.]*";
//if u need to think of much better email validation..
//String pattern="^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
System.out.println("Enter your Email here :");
flag=scanner.next().matches(pattern);
if(!flag){
System.out.println("Not a valid Email.");
}else{
System.out.println("Valid Email.");
}
}while(!flag);
}

You can use this code as class valid.
class valid {
String scan2;
char amper = '#';
boolean isFound = false;
valid(String scan1) {
scan2 = scan1;
for (int i = 0; i < scan2.length(); i++) {
if (scan2.charAt(i) == amper) {
isFound = true;
}
}
if(isFound) {
System.out.println("Seems like valid email.");
}
}
}
This code based on your class valid and continue some critical errors. As example : "What happen if user input contains more # characters.

Related

Checking if a string contains only digits ? (isDigitMethod required)

The user should give a string, where we should check if all characters are numbers.
If all are digits, we will get one message that the password is with digits and move on with the program. If any of them (or all) is not a digit, then the user should enter password again.
(E.g. 465486 is acceptable. hell3429384 or sfdkjsfkj is not acceptable)
Apparently, my code is not working correctly, since whether I give a number or a letter to the password, I get the same result.
Am I looping something wrong, or am I using the isDigit method wrong?
import java.util.*;
public class Password {
public static void main(String[] args) {
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
int length = pass.length();
boolean isadigit;
for(int i = 0; i < length; i++) { /*looping each character one by one*/
char character= pass.charAt(i);
if (Character.isDigit(i)) { /*checking if each character is digit*/
isadigit = true; /* if it is, give the value to isadigit true*/
System.out.println("PASSWORD is w digits");
}
else {
System.out.println("PASSWORD w/out digits");
passn.nextLine();
}
}
}
}
If you can use java-8 there is one-liner:
pass.chars().allMatch(Character::isDigit)
You are not checking each character, but each index value.
Change
if(Character.isDigit(i))
to
if(Character.isDigit(character))
Also: you don't break out of the loop when you encounter a non-digit...
A side note if you are on Android:
You can use TextUtils.isDigitsOnly() directly, e.g.
TextUtils.isDigitsOnly(myString)
And just in case, an empty string is digit only because it doesn't contain any non-digit; also this method is not null-tolerant.
To be honest: You could write code like you did. But it would be better to use a regular expression on that. You want to know, if a certain String only contains digits. Here is the code:
String foo = "My_pwd_is_wrong_123!";
String bar = "123";
boolean foo_ok = foo.matches("^[0-9]*$") // Will be "false"
boolean bar_ok = bar.matches("^[0-9]*$") // Will be "true"
Ok, in that case: Your Problem is, that you continue your loop after identifiyng a non-digit in one Password. You need to BREAK your loop, as soon as you find a non-digit in the pwd:
public class TEST {
public static void main(String[] args) {
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
int length = pass.length();
boolean isadigit = true;
for(int i = 0; i<length; i++) { /*looping each character one by one*/
char character= pass.charAt(i);
if (!Character.isDigit(character)) { /*checking if current character is digit*/
isadigit = false; /* if it is not, give the value to isadigit false*/
break;
}
}
if(isadigit)
System.out.println("PASSWORD is w digits");
else
System.out.println("PASSWORD w/out digits");
}
}
Please see this sample implementation
boolean isDigit = false;
for (int i = 0; i < length; i++) {
char character = pass.charAt(i);
if (Character.isDigit(character)) {
isDigit = true;
} else {
passn.nextLine();
}
}
if (isDigit) {
System.out.println("PASSWORD is w digits");
} else {
System.out.println("PASSWORD w/out digits");
}
In Kotlin, you can use
text.all { it.isDigit() }
try to parse the string to Integer.
catch the exception
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
try
{
Integer.parseInt(pass);
System.out.println("Digital password!");
}
catch(NumberFormatException nfe){
System.out.println("without digit password!");
}

Java how to continue current loop when condition is false

I am having an issue whereby whenever input validation is incorrect it breaks out of my current loop and continues with the next method can anyone help me so that when condition is false it re-asks for the same input until it meets the condition. Here's my source code for my method class
public class Student {
public int gradePt;
public int i;
public int credSum = 0;
public double gradeCredSum = 0;
public double gpa;
String [] moduleName;
String [] moduleGrade;
int [] moduleCred ;
Module[] modules;
public void createModules(){
getModuleNo();
modules = new Module[i];
moduleName = new String[i];
moduleGrade = new String[i];
moduleCred = new int[i];
getModule();
getGrade();
getCred();
for (int j = 0; j < modules.length; j++) {
modules[j] = new Module(moduleName[j],moduleCred[j],moduleGrade[j]);
}
}
public void getModuleNo(){
do{
String input = JOptionPane.showInputDialog(null,
"How many modules did you take?","Input");
int a = Integer.parseInt(input);
if (a<1 || a>8){
JOptionPane.showMessageDialog(null,
"Invalid input please enter a number greater than 0",
"Error",JOptionPane.ERROR_MESSAGE);
break;
} i = a;
}while(i<1 || i>8);
}
public void getModule(){
for (int i=0;i<moduleName.length;i++){
String input = JOptionPane.showInputDialog(null,
"Enter the name of module #"+(i+1));
moduleName[i] = input;
if (input == ""){
JOptionPane.showMessageDialog(null,
"Invalid input, module name cannot be blank","Error",JOptionPane.ERROR_MESSAGE);
break;
}
}
}
public void getGrade(){
for (int i=0;i<moduleGrade.length;i++){
String input = JOptionPane.showInputDialog(null,
"Enter grade (A,B,C,D,F) for module #"+(i+1));
moduleGrade[i] = input;
if (!"A".equals(input) && !"B".equals(input) && !"C".equals(input) && !"D".equals(input) &&
!"F".equals(input) && !"a".equals(input) && !"b".equals(input) && input!="c" &&
!"d".equals(input) && !"f".equals(input)){
JOptionPane.showMessageDialog(null,
"Invalid input!"+"\n"+"Please enter A,B,C,D or F","Error",JOptionPane.ERROR_MESSAGE);
break;
}
moduleGrade[i] = input;
}
}
public void getCred(){
for (int i=0;i<moduleCred.length;i++){
String input = JOptionPane.showInputDialog(null,
"Enter credit units for module #"+(i+1));
moduleCred[i] = Integer.parseInt(input);
if (moduleCred[i]<1 || moduleCred[i]>8){
JOptionPane.showMessageDialog(null,
"Invalid input!"+"\n"+"Please enter a number form 1 to 8","Error",JOptionPane.ERROR_MESSAGE);
break;
}
}
}
This is a common process. You keep asking for input, checking it each time until the input is valid.
Pseudocode:
repeat
display("Please enter your input: ")
input <- getInput()
until (isValid(input))
There are many loops in your program asking for input. so here is some code for your problem
boolean inputOk=false;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
do{
// ask for input
System.out.println("Enter the value");
// capture input
String input = reader.readLine();
// evaluate input
if(input.equals("ok"))
inputOk = true; // set flag if input is ok
}while(!inputOk); // if flag is ok then exit loop
I count four getter methods where you use a JOptionPane to gather user input. In the code snippet below, I have refactored getGrade() such that it continues to prompt the user for input, for a given module grade, until valid input is received.
While the fix for your three other methods is not given here, you can try following a similar pattern.
public void getGrade() {
String invalidInputMsg = "Invalid input!" + "\n" + "Please enter A,B,C,D or F";
for (int i=0; i < moduleGrade.length; i++) {
do {
String enterGradeMsg = "Enter grade (A,B,C,D,F) for module #" + (i+1)";
String input = JOptionPane.showInputDialog(null, enterGradeMsg);
if (input.length() == 1 &&
"ABCDF".indexOf(input.toUpperCase().charAt(0)) != -1) {
moduleGrade[i] = input;
break;
}
else {
JOptionPane.showMessageDialog(null, invalidInputMsg, "Error",
JOptionPane.ERROR_MESSAGE);
}
} while(true);
}
}
If the input be valid, then break will end the do loop, and the next value of i will be used in the for loop, should it be available. If the input be invalid, then the do loop will continue and prompt the user again for input.

clearing a java string after loop

I am new to Java and am creating a project for class that basically asks the user to input a string, and then tests the string and prints whether or not it is a palindrome (the same forwards as backwards... i.e. mom or dad or racecar)
I have gotten the code to work, however i have a loop setup to rerun the program or quit at the end. My problem is that when you rerun the program and enter another String input then it's adding it to the original string.
How can I reset or delete the String input each time so that it starts fresh?
Thank you for any help! Also please note, there may be better or faster ways to accomplish what I have done here but my knowledge of java is limited and I am just getting started, so I have used the knowledge that I have thus far learned. Thanks!!
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
String redoAnswer; // answer to rerun program
int length; //length of word entered by user
boolean test;
boolean redo; // boolean to rerun program
boolean exit; // boolean to validate exit/rerun
Scanner scan = new Scanner(System.in);
do {
redo = true;
exit = true;
System.out.println("Please enter a string: ");
input = scan.nextLine();
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
do {
System.out.println("Please type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
exit = false;
redo = true;
continue;
} else if (redoAnswer.equals("q")) {
exit = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that.");
continue;
}
} while (exit);
} while (redo);
} //end main
} //end class
Ok, figured it out thanks to your guys' help... also rewrote the code so that you can just keep entering new strings or type q to quit instead of the redo question at the end. Hopefully this is cleaner!
import java.util.Scanner;
public class Palindrome_Test {
public static void main(String[] args) {
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
int length; //length of word entered by user
boolean redo = true; // boolean to rerun program
Scanner scan = new Scanner(System.in);
do {
System.out.println("Please enter a string, or type Q to quit: ");
input = scan.nextLine();
if (input.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
redo = false;
} else {
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
reverse = "";
}
} while (redo);
} //end main
} //end class
At the end of your while loop add reverse = "";
You'll notice that I moved the following -
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
Inside of the first loop. Although you could simply reset both variables at the end of the loop...
input = "";
reverse = "";
There is no need to (Although, they both work!). By dealing with the scope of the variable inside of the loop, it will essentially "refresh" each time the loop executes.
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
// String input = ""; // Word entered by user
// String reverse = ""; //Reverse of String input
String redoAnswer; // answer to rerun program
int length; //length of word entered by user
boolean test;
boolean redo; // boolean to rerun program
boolean exit; // boolean to validate exit/rerun
Scanner scan = new Scanner(System.in);
do {
redo = true;
exit = true;
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
System.out.println("Please enter a string: ");
input = scan.nextLine();
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
do {
System.out.println("Please type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
exit = false;
redo = true;
continue;
} else if (redoAnswer.equals("q")) {
exit = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that.");
continue;
}
} while (exit);
} while (redo);
} //end main
} //end class

How to use else statement to check string entry

I have added an array containing string values in my programme where I want to add an else statement so that if someone enters a value that is not contained in the array, in would print out a message invalid entry.
I have written this in the programme but if a correct value is entered the invalid entry still appears when I run the code.
Enter your name
barry
you are verified you may use the lift
Invalid entry
Invalid entry
Invalid entry
This is what I get
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
// array containing usernames
String [] name = {"barry", "matty", "olly","joey"}; // elements in array
System.out.println("Enter your name");
String name1 = kb.nextLine();
for (int i = 0; i < name.length; i++) {
if(name[i].equals(name1)) {
System.out.println("you are verified you may use the lift");
}else{System.out.println ("Invalid entry");
}
}
Instead of looping over the array, you could just convert the array to a list in use contains:
System.out.println("Enter your name");
String name1 = kb.nextLine();
if (Arrays.asList(name).contains(name1)) {
System.out.println("you are verified you may use the lift");
} else {
System.out.println ("Invalid entry");
}
You can add a boolean variable and keep there information if user has been found.
Try this code:
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = { "barry", "matty", "olly", "joey" }; // elements in
// array
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift");
b = false;
break;
}
}
if (b) {
System.out.println("Invalid entry");
}
}
I think it's because of how you iterate and compare. You compare the value entered to all the names with a for loop. Barry doesn't equal "matty", "olly" or "joey", but your for loop still compares all of them.
Your problem is that if outputs on all comparisons.
I would recommend setting a boolean before the loop, and if it finds a match - set that boolean to true.
Then when the loop has ended, simply check if the boolean is true or false, and output the desired code.
Example:
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
// array containing usernames
String [] name = {"barry", "matty", "olly","joey"}; // elements in array
System.out.println("Enter your name");
String name1 = kb.nextLine();
Boolean foundMatch = false;
for (int i = 0; i < name.length; i++) {
if(name[i].equals(name1))
foundMatch = true;
}
if(foundMatch)
System.out.println("you are verified you may use the lift");
else
System.out.println ("Invalid entry")
}
You can specify a boolean value to save your status.
boolean contais = false;
for (int i = 0; i < name.length; i++) {
if(name[i].equals(name1)) {
contais = true;
break;// to stop looping
}else{contais = false;}
}
if(contais) {
System.out.println("you are verified you may use the lift");
else {
System.out.println ("Invalid entry");
}
Your code :
if(name[i].equals(name1))
Try This :
if(name[i].equalsIgnoreCase(name1))

Java code Check Password for Letter and Digit?

EDIT--VERSION
The first post was confusamagin. My assignment is to create a password prompt program. The password needs to be checked to see if it does have at least one digit and one letter in it. Also the password length must be between 6 - 10.
My problem is trying to figure out how see if a digit and letter exist the password. In the check password area I am not sure where to begin really. I am not sure how to see if it has a Letter and a Digit in one. I know how to do either or by using a for statement to count and check but all it does is check to see rather it contains all letters or all digits.
Below is what I have so far...
import java.util.Scanner;
class Password {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//------ENTER A USERNAME
System.out.println("Welcome please enter your username and password.");
System.out.print("Username >>");
input.nextLine();
//------PASSWORD AUTHENTICATION BEGIN
String password = enterPassword();
while ( !checkPassword(password) ) {
System.out.println("Password must be 6 - 10 characters long!");
password = enterPassword();
}
//------PASSWORD VERIFY
String passwordverify = enterPassword();
while (!password.equals(passwordverify)){
System.out.println("ERROR - Passwords DO NOT MATCH Re-Enter Passwords Again");
password = enterPassword();
}
//------ACCEPT PASSWORD
System.out.println("Username and Password Accepted!");
}
//--ENTER PASSWORD STATEMENT
public static String enterPassword(){
String password;
Scanner input = new Scanner(System.in);
System.out.print("Password >>");
password = input.nextLine();
return password;
}
//--BOOLEAN CHECK PW
public static boolean checkPassword(String password){
int length;
length = password.length();
if (length < 6 || length > 11){
return false;
}
for (int i = 0; i < password.length();i++){
if (!Character.isLetter(password.charAt(i)))
return false;
}
return true;
}
}
public static boolean checkPasswordLetter(String password){
for (int i = 0; i < password.length();){
if (!Character.isLetter(password.charAt(i))){
return false;
}
}
return true;
}
Here you didn't increment variable i , need in for i++ or your loop is going forever if is not letter, same and in checkPasswordDigit
checkPasswordLetter and checkPasswordDigit will only return true if ALL chars are letters/digits respectively. Is this what you meant?
First off... It's not that Java is not looping or checking Boolean. Java is doing what you are telling it to do.
Now, what you want to do is different than what you are doing.
What you need to do is something like:
public static void main(String[] args) {
// ...
String password = enterPassword();
while ( !isPasswordValid(password) ) {
password = enterPassword();
}
System.out.println("Username and Password Accepted!");
}
public static boolean isPasswordValid(String password) {
// return true if and only if password:
// 1. has 6-10 characters
// 2. contains at least one digit
// 3. contains at least one character
// print messages accordingly
}
There are two things wrong.
Your letter checking is failing on the first non-letter. Same thing happening with your digit checking. You only want to reject if every character is a non-letter, for example. So logic error.
You have three loops. Bad idea, because if you pass the length check once, it is never going to be checked again. Consider what would happen if someone entered: 12345678. Length ok, but no letter. Ok, now enter: a1. Length not checked again.
import java.util.Scanner;
import java.util.*;
import java.lang.String;
import java.lang.Character;
public class CheckingPassword
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter a Password: ");
String password = input.next();
if (isValid(password)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
public static boolean isValid(String password) {
if (password.length() < 9) {
return false;
}
else {
char c = 0 ;
int count=0;
System.out.println(password.length());
for (int i = 0;i<=password.length()-1; i++)
{
c = password.charAt(i);
System.out.println(c);
if (!Character.isLetterOrDigit(c))
{
return false;
}
else if (Character.isDigit(c))
{
count++;
if(count==3)
{
return false;
}
}
}
return true;
}
}
}
import java.util.Scanner;
public class password{
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a string
System.out.print("Enter a password ") ;
String s = input.nextLine();
if(isValid(s))
System.out.println(s + " is a valid password");
else
System.out.println(s + " is not a valid password");
}
public static boolean isValid(String s )
{
int i = 0,j=0;
if(s.length()>=8)
{
for(i=0;i<s.length();i++)
{
//if(Charcter.isLetter(s.charAt(i))||Digit.isLetter(s.charAt(i)))
if (Character.isLetterOrDigit(s.charAt(i)))
{
if(Character.isDigit(s.charAt(i)))
j++;
}
}
}
else
return false;
if(j>=2)
return true;
return false;
} }

Categories

Resources