Validate User Input Using Java Chars and Strings - java

I have seen this asked 2x, but the correct response I need has not been addressed.
In this assessment,
you will design and code a Java console application that
validates the data
entry
of a course code (like IT4782)
and
report
back if the
course code is valid or
not
valid.
The
application
uses the Java char
and
String data types to implement
the validation.
You
can
use
either
the
Toolwire environment
or your
local
Java
development
environment
to complete this
assignment.
The requirements of
this application are
as follows:
The application is to read
a course code
entered
by the user
from the
keyboard.
The course code
is made
of 5 characters and should
follow
these
Rules:
First
character
is always
an
upper
case I
or a lower
case i
Second character
is always an upper
case
T or
a lower
case t
Third,
fourth,
fifth,
and sixth characters
are always digits (0-
9)
The application then validates the course code against
above the rules and prints a
message
If the
course code
is valid
or not.
If the course code is not
valid,
the application should print
a message
explaining why
the course
code is not
valid.
Output should look like this:
Here is my code, I cannot get the code to produce the pictured results. It outputs all the invalid messages.
package u4a1_validatecoursecode;
import java.util.Scanner;
public class U4A1_ValidateCourseCode {
public static void main(String[] args) {
// Larry Copy
Scanner s = new Scanner(System.in);
System.out.print("Enter a course code to validate (e.g. IT4782) : ");
String code = s.nextLine();
if (validateCode(code)) {
System.out.println("Course code: " + "" + code + "" + " is valid.");
} else {
System.out.println("Not valid code");
}
}
private static boolean validateCode(String code) {
if (code.length() != 6) {
return false;
} else {
//First character is always an upper case I or a lower case i
if (code.charAt(0) != 'I' && code.charAt(0) != 'i') {
return false;
}
System.out.println("integer is not an I or i");
// Second character is always an upper case T or a lower case t
if (code.charAt(1) != 'T' && code.charAt(1) != 't') {
return false;
}
System.out.println("integer is not a T or t");
// Third, fourth, fifth, and sixth characters are always digits (0-9)
if (!Character.isDigit(code.charAt(2))) {
return false;
}
System.out.println("integer 3 is not a number");
if (!Character.isDigit(code.charAt(3))) {
return false;
}
System.out.println("integer 4 is not a number");
if (!Character.isDigit(code.charAt(4))) {
return false;
}
System.out.println("integer 5 is not a number");
if (!Character.isDigit(code.charAt(5))) {
return false;
}
System.out.println("integer 6 is not a number");
return false;
}
}
}

When you return false; the code after is not executed so you'll never see why it returns
If you return only false the test will never pass, you need a variable to validate or not the code
If it goes in one if (not valid) you'll get the message, and the valid will be false
private static boolean validateCode(String code) {
if (code.length() != 6) {
return false;
} else {
boolean valid = true;
//First character is always an upper case I or a lower case i
if (code.charAt(0) != 'I' && code.charAt(0) != 'i') {
System.out.println("integer is not an I or i");
valid = false;
}
// Second character is always an upper case T or a lower case t
if (code.charAt(1) != 'T' && code.charAt(1) != 't') {
System.out.println("integer is not a T or t");
valid = false;
}
// Third, fourth, fifth, and sixth characters are always digits (0-9)
if (!Character.isDigit(code.charAt(2))) {
System.out.println("integer 3 is not a number");
valid = false;
}
if (!Character.isDigit(code.charAt(3))) {
System.out.println("integer 4 is not a number");
valid = false;
}
if (!Character.isDigit(code.charAt(4))) {
System.out.println("integer 5 is not a number");
valid = false;
}
if (!Character.isDigit(code.charAt(5))) {
System.out.println("integer 6 is not a number");
valid = false;
}
return valid;
}
}

You are using too much line of code:
Here what I do:
private static boolean validateCode(String code,String validCode) {
boolean b=true;
if (code.length() != 6) {
return false;
}
for(int i=0;i<code.length();i++){
if(code.toLowerCase().charAt(i)!=validCode.toLowerCase().charAt(i) && i<2){
System.out.println("Character at "+i+" position is not an "+ validCode.charAt(i));
b= false;
}
if(Character.isDigit(code.charAt(i)) && i>2){
System.out.println("Character at "+i+" is not a digit");
b= false;
}
}
return b;
}

Related

Input Error. Still uses old input even after taking new input

I have to make the code such that the user cannot enter a wrong value.
public static String getFraction() {
Scanner s = new Scanner(System.in);
String fraction = s.next();
if (validFraction(fraction)){
return fraction;
}
else {
System.out.print("Invalid fraction. Please enter a
fraction (a/b) or integer (a), where a and b are
integers and b is not zero : ");
getFraction();
}
Here when the user enters a wrong value it prompts the user to put a new value but it still takes the old value.
return null;
}
For example, say if I input a/b it prompts me to input again but since I use a parseInt method later in the code it shows me an error like :
Exception in thread "main" java.lang.NumberFormatException: For
input string: "a"
at java.base/java.lang.NumberFormatException.forInputString(Num
berFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at FractionCalculator.numerator(FractionCalculator.java:105)
at FractionCalculator.main(FractionCalculator.java:15)
Valid Fraction function :
public static boolean validFraction(String f) {
if (f.contains("/")) {
int n = f.indexOf("/");
String num = f.substring(0, n);
String den = f.substring(n+1);
for (int i = 1; i<n; i++) {
char a = num.charAt(i);
char b = den.charAt(i);
if (a == '-' || b == '-') {
return false;
}
}
f.replaceAll("[-]", "");
if (isNumber(num, den)) {
if (den.equals("0"))
return false;
else
return true;
}
}
else {
if (f.matches("^[0-9]+$"))
return true;
}
return false;
}
The exception seems to be coming from a place where Strings (a, b) are getting parsed as Integers.
If you intend to actually do so and check if the string is numeric or not, then it's advisable to catch NumberFormatException and return the status accordingly as follows:
private static boolean isNumber(String string)
{
try
{
Integer.parseInt(string);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}

Program which prompts the user to enter a password and checks conditions

So I have been working on this program which prompts the user to enter a password but the password must be at least 8 characters long and only contain letters and digits. Here is my code:
import java.util.Scanner;
public class Password {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Please enter a password: ");
String password = input.nextLine();
boolean valid = true;
if (valid(password)) {
System.out.println("Password accepted!");
}
}
public static boolean valid(String password) {
if (password.length() < 8) {
System.out.println("Password must have at least eight characters.");
return false;
} else {
char c;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if (password.matches("[0-9a-zA-Z]+")) {
return true;
} else {
System.out.println("Password must only contain letters and digits.");
return false;
}
}
return true;
}
}
}
The problem I'm having is that when I enter an input like $$$, the only output is "Password must have at least eight characters", but I need both this output and ""Password must only contain letters and digits." In other words, I need the program to check if both conditions are false and display both outputs. How would I go about doing that?
Also, if you have any suggestions on how to make my program better, that would be helpful as well.
Thank you!
You could simply move your valid variable from the main method to the valid method and set it to false for every condition not met. Only return in the end after every condition has been checked.
public static boolean checkValid(String password) {
boolean valid = true;
if (password.length() < 8) {
System.out.println("Password must have at least eight characters.");
valid = false;
}
if(!password.matches("[0-9a-zA-Z]+")) {
System.out.println("Password must only contain letters and digits.");
valid = false;
}
return valid;
}
And you don't need to iterate through every character of the password to match the regex.

Java: checking if a phone number fits a valid format

I am trying to find if a phone number fits the format (xxx)xxx-xxxx where x is a digit. First, I have the program for the length and the '(',')', and '-'. When I type in something that doesn't work, I get the logical output. However, when I type in a properly formatted number, my program doesn't return anything.
import java.util.Scanner;
public class Program04 {
public static void main(String args[])
{
Scanner stdIn = new Scanner(System.in);
String pN;
System.out.print("Please enter a phone number (ddd)ddd-dddd :");
pN = stdIn.nextLine();
char a = pN.charAt(1);
char b = pN.charAt(2);
char c = pN.charAt(3);
char d = pN.charAt(5);
char e = pN.charAt(6);
char f = pN.charAt(7);
char g = pN.charAt(9);
char h = pN.charAt(10);
char i = pN.charAt(11);
char j = pN.charAt(12);
if (pN.length() == 13 && pN.charAt(0)=='(' && pN.charAt(4)== ')' && pN.charAt(8)=='-')
{
if (a>=0 && a<=9)
{
if (b>=0 && b<=9)
{
if (c>=0 && c<=9)
{
if (d>=0 && d<=9)
{
if (e>=0 && e<=9)
{
if (f>=0 && f<=9)
{
if (g>=0 && g<=9)
{
if (h>=0 && h<=9)
{
if (i>=0 && i<=9)
{
if (j>=0 && j<=9)
{
System.out.print("This is a valid phone number!");
}
}
}
}
}
}
}
}
}
}
}
else System.out.println("Not a vaid phone number.");
}
}
It's easier to use pattern-matching (regex) for validation:
...
pN = stdIn.nextLine();
System.out.println(pN.matches("\\(\\d{3}\\)\\d{3}-\\d{4}"));
Even if you want to have it check if each character is a digit, using so many nested if's is not the way to go. Instead, define a simple method that applies the check, say:
private static boolean isDigit(char x) {
return x>=0 && x<=9;
}
and then do:
if ( isDigit(a) && isDigit(b) && ...) {
return true;
}
else {
return false;
}
If you're not allowed to use RegEx or if it is too difficult to understand, try simplifying your nested if's by a simple switch inside a loop, it is much more readable and maintenance is the easiest :
public static void main(String[] args) {
String pn = scan.nextLine();
boolean valid = true;
if (pn.length() == 13){
for (int i = 0 ; i < 13 ; i++){
switch(i){
case 0 : valid = pn.charAt(0) == '(';break;
case 4 : valid = pn.charAt(4) == ')';break;
case 8 : valid = pn.charAt(8) == '-';break;
default : valid = Character.getNumericValue(pn.charAt(i)) >= 0 && Character.getNumericValue(pn.charAt(i))<= 9 ; break;
}
if (!valid) break;
}
if (!valid) System.out.println("Invalid number");
}else{
valid = false;
System.out.println("Invalid length");
}
if (valid){
System.out.println(pn + " is a valid telephone number");
}
}
Also, to avoid working with the ASCII value of a char, try using the Character.getNumericValue(Char c) method. It returns a numeric that you can use for your tests, like above.
It is better to use regex in this case:
You can use following :
String pattern = "(\\(\\d{3}\\)\\d{3}-\\d{4})";
Pattern r = Pattern.compile(pattern);
pN = stdIn.nextLine();
Matcher m = r.matcher(pN);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}

Java error: <identifier> expected unable to compile

I am trying to finish a homework assignment and keep getting two errors and cannot figure out how to fix them. Here is the code:
import java.util.Scanner;
public class GoughAndreaProg5
{
public static void main (String[] args)
{
Scanner stdIn = new Scanner(System.in);
System.out.println("Enter a password that meets the following rules: ");
System.out.println("");
System.out.println("Is atleast 8 characters long");
System.out.println("Contains atleast 1 lower letter character");
System.out.println("Contains atleast 1 upper letter character");
System.out.println("Contains atleast 1 numeric digit");
System.out.println("Contains atleast 1 special character from the set: !##$%^&*");
System.out.println("Does not contain the word \"and\" or the word \"end\"");
System.out.println("");
String myInput = stdIn.nextLine();
boolean digit = false;
boolean upperCase = false;
boolean lowerCase = false;
for(int x=0; x<myInput.length(); x++)
{
if (Character.isDigit(myInput.charAt(x)))
digit = true;
if(Character.isUpperCase(myInput.charAt(x)))
upperCase = true;
if(Character.isLowerCase(myInput.charA(x)))
lowerCase = true;
}
boolean validLength = true;
if (myInput.length() < 8)
{
System.out.println("Must be at least 8 characters long");
validLength = false;
}
boolean special = false;
if(myInput.indexOf('!') != -1 | myInput.indexOf('#') != -1 || myInput.indexOf('#') != -1 || myInput.indexOf('$') != -1 || myInput.indexOf('%') != -1 || myInput.indexOf('^') != -1 || myInput.indexOf('&') != -1 || myInput.indexOf('*') != -1)
special = true;
else //no special character
{
System.out.println("Must contain a special character");
}
boolean word = false;
if (myInput.indexOf("and") != -1 || myInput.indexOf("end"));
{
word = true;
System.out.println("Contains the string \"and\" or the word \"end\"");
}
if(!digit)
System.out.println("Must have a numeric digit");
if(!upperCase)
System.out.println("Must have an upper case");
if(!lowerCase)
System.out.println("Must hava a lower case");
//output valid or not
if (validLength && special && !word && upperCase && lowerCase && digit)
System.out.println("valid");
else
System.out.println("not valid");
} //end main method
public static void System.out.println(String inStr)
{
System.out.println(inStr);
} //end of alt string print method
} //end of class
The errors are:
C:\Users\gougha\Documents\Park\Java Class\myJavaPgms\GoughAndreaProg5.java:76: error: '(' expected
public static void System.out.println(String inStr)
^
C:\Users\gougha\Documents\Park\Java Class\myJavaPgms\GoughAndreaProg5.java:76: error: <identifier> expected
public static void System.out.println(String inStr)
^
I have tried every thing I can think of. I'm sure it's an easy fix, but this is all so new to me and I can't see it. Thank you!
There are several compile errors with your code
To start
public static void System.out.println(String inStr)
should be (though you don't use it so I suggest just remove this method)
public static void println(String inStr)
Then
if (myInput.indexOf("and") != -1 || myInput.indexOf("end"));
should be
if (myInput.indexOf("and") != -1 || myInput.indexOf("end") != -1);
Finally
if(Character.isLowerCase(myInput.charA(x)))
should be
if(Character.isLowerCase(myInput.charAt(x)))
You do not need to create this method public static void System.out.println(inStr). Infact the syntax is also wrong. You just need to provide a method name when you create it. Not the class name along with it.
// Not required at all
public static void System.out.println(String inStr)
{
System.out.println(inStr);
}
System.out.println() is the inbuilt method to print values to the console. So just use System.out.println(inStr) in your main method, whenever you need to print something on the System's output console.

Return statement error, return null instead

I'm trying to use a method to display an error message if the user enters a number other than 1 - 4, but I'm getting a missing return statement error.
public int CheckAnswers () {
boolean incorrectAnswer = true;
do {
playerAnswer = CheckAnswers();
if (playerAnswer < 1 || playerAnswer > 4) {
System.out.println("You have entered an incorrect number.");
System.out.println("Please enter a number between 1 and 4");
} else {
return (playerAnswer); }
} while (incorrectAnswer);
}
The error points to the last bracket. I've done some looking around online and I think the problem is that I don't have a return statement in both parts of the if-else statement. But if they have entered an incorrect number I don't want to return anything. I tried using the below code unsuccessfully.
public int CheckAnswers () {
boolean incorrectAnswer = true;
do {
playerAnswer = CheckAnswers();
if (playerAnswer < 1 || playerAnswer > 4) {
System.out.println("You have entered an incorrect number.");
System.out.println("Please enter a number between 1 and 4");
return (null);
} else {
return (playerAnswer); }
} while (incorrectAnswer);
}
The compiler's analysis does not determine that
do {
playerAnswer = CheckAnswers();
if (playerAnswer < 1 || playerAnswer > 4) {
System.out.println("You have entered an incorrect number.");
System.out.println("Please enter a number between 1 and 4");
} else {
return (playerAnswer); }
} while (incorrectAnswer);
is indeed an infinite loop, and the only way to get out of the loop is the return in the else branch. (Since incorrectAnswer cannot be changed except by cosmic rays flipping bits, it is, but the compiler isn't convinced.)
Thus it wants a return in case the loop is left in a different way.
If you make the loop condition a literal true,
do {
// code
} while(true);
the compiler will know that the loop can only be left via the return in the else branch (you can and should eliminate the boolean incorrectAnswer; then).
As yannis hristofakis observed, calling playerAnswer = CheckAnswers(); immediately in the loop causes an infinite recursion, and that will lead to a stack overflow. You need to call a method that obtains some input from the user instead there.
I'm amazed that 3 answers were posted and none of them mentioned that
It's an eternal procedure since you call recursevly the CheckAnswers method.
You can't return null for primitive return type methods.
I think you should skip the parenthesis.
return playerAnswer;
Just do a return statement of return -1 right after the do while.
You will not ever reach that code, but it will make the compiler happy who is not able to understand the logic of your code and just sees that there are possible execution paths that don't return anything.
public int CheckAnswers () {
boolean incorrectAnswer = true;
do {
playerAnswer = CheckAnswers();
if (playerAnswer < 1 || playerAnswer > 4) {
System.out.println("You have entered an incorrect number.");
System.out.println("Please enter a number between 1 and 4");
}
else {
return (playerAnswer);
}
} while (incorrectAnswer);
return -1; //unreachable statement
}
Try this:
public int CheckAnswers () {
boolean incorrectAnswer = true;
do {
playerAnswer = CheckAnswers();
if (playerAnswer < 1 || playerAnswer > 4) {
System.out.println("You have entered an incorrect number.");
System.out.println("Please enter a number between 1 and 4");
} else {
incorrectAnswer = false;
}
} while (incorrectAnswer);
return playerAnswer;
}

Categories