I'm having difficulty ensuring that doubles are validated correctly in my program. A user can enter an amount to deposit into the account, which should be a double (I know, it's not what I should be using, but it's part of the assignment guidelines). Theoretically, the user should be able to deposit any amount- not just £30, but say, £15.23.
This is the validation I currently have, which allows numbers, but prevents the entry of a full stop, which creates a number of problems.
Here is the code I have so far:
public static String getBalanceValidation()
{
//Allow user input capabilities
Scanner input = new Scanner (System.in);
//Declare variables needed for validation
double dblInput = 0; //dblInput is set as 0
String strNumber = ""; //strNumber is blank
boolean bolSuccessful, bolNumeric;
int intCount;
char charLetter;
do
{
//set bolSuccessful and bolNumeric as true
bolSuccessful = true;
bolNumeric = true;
try //try user input
{
System.out.println("Enter the balance to be deposited: "); //User prompt
strNumber = input.next(); //User input as string
dblInput = Double.parseDouble(strNumber) ; //String input converted to double
}// end of try
catch (NumberFormatException e) //NumberFormatException disallows letters or symbols in value
{
System.out.println("Deposit value cannot contain letters!"); //Error message
bolSuccessful = false; //set bolSuccessful as false
continue; //Return to try
}//end of number format catch
//create for loop which checks each character throughout the string
for (intCount = 0; intCount < strNumber.length(); intCount++)
{
charLetter = strNumber.charAt(intCount); //charLetter is the alphanumeric value of a character in the string at the point dictated by intCount
if (!(charLetter >= '0') && (charLetter <= '9' ) //if charLetter is not between 0 and 9
|| (charLetter == '.')) //or charLetter is not a full stop
{
bolNumeric = false; //Set bolNumeric as false
}//end of if construct
}//end of for loop
if (!bolNumeric) //if bolNumeric is false
{
System.out.println("Incorrect input format! The balance must be numbers only!"); //Error message
bolSuccessful = false; //Set bolSuccessful as false
}//end of if construct
}while (!bolSuccessful); //While bolSuccessful is false, return to top
return strNumber; //return strNumber to be used in main method
//end of do method
}//end of getBalanceValidation method
I'm not sure whether it's because I've used NumberFormatException (is there something else for double?)
Many thanks
You have 2 errors in your boolean expression :
if (!(charLetter >= '0') && (charLetter <= '9' ) || (charLetter == '.'))
This condition is equivalent to :
if ((charLetter < '0') && (charLetter <= '9' ) || (charLetter == '.'))
Which can be simplified to :
if ((charLetter < '0') || (charLetter == '.'))
So the ! should be applied to the first two parts of the expression :
if (!( (charLetter >= '0') && (charLetter <= '9') ) || (charLetter == '.'))
Moreover, since . is not a number, this expression is equivalent to :
if (!( (charLetter >= '0') && (charLetter <= '9') ))
You probably meant && not || :
if (!( (charLetter >= '0') && (charLetter <= '9' ) ) && (charLetter != '.'))
Which means if(not_a_number AND not_a_full-stop)
You can double number = input.nextDouble(); instead of strNumber = input.next();. This would allow you to input the number directly as double instead of String.
You would have to handle InputMismatchException in your catch block, and you are good to go. You won't need to validate to check the inclusion of ..
It would be much easier using a regex:
bolNumeric = strNumber.matches("[1-9][0-9]*(\\.[0-9]{1,2})?");
Explanation: The first number has to be within 1-9. Then as many as you want (including none) other numbers may follow. This is optionally followed by a dot, and then at least one, max 2 more digits.
Related
I am trying to get the code to check for special characters entered, however, I am not getting any validation errors when special characters are not entered in the password. Is there a reason why special characters are not been identified? All the other password validation checks work fine
//package sampleProject;
import java.util.*;
import java.util.Scanner;
public class Lab7 {
public static void main(String []args){
// Specify the maximum number of letters in a password
final int MAX=10;
int invalidCount = 0;
// Specifying the number of uppercase letters in password
final int MIN_Uppercase=1;
// Specifying the minimum lowercase letters in password
final int NUM_Digits=2;
// Specify the minimum number of special case letters
final int Special=1;
// Count number of uppercase letters in a password
int uppercaseCounter=0;
// Count digits in a password
int digitCounter=0;
// count special case letters in a password
int specialCounter=0;
System.out.println("Enter the password\n");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
for (int i=0; i < password.length(); i++ ) {
char c = password.charAt(i);
if(Character.isUpperCase(c))
uppercaseCounter++;
else if(Character.isDigit(c))
digitCounter++;
if(c == '$' || c == '#' || c == '?' || c == '!' || c == '_' || c == '=' || c == '%'){
specialCounter++;
}
}
if (password.length() >= MAX && uppercaseCounter >= MIN_Uppercase && specialCounter == 1 && digitCounter == 2 || digitCounter == 3) {
System.out.println("Valid Password");
}
else {
System.out.println("Your password does not contain the following:");
if(password.length() < MAX)
System.out.println("Enter atleast 10 characters");
if (uppercaseCounter < MIN_Uppercase)
System.out.println("Enter at least 1 uppercase character");
if(digitCounter != 2 || digitCounter != 3)
System.out.println("Enter either 2 or 3 digits");
if(specialCounter > 1)
System.out.println("Password should contain only 1 special characters");
}
}
}
What you should do this instead in this line :
if(specialCounter != 1)
System.out.println("Password should contain only 1 special characters");
if it is not equal to 0, it will throw the exception. The != means not equal, so if it is less or above 1, It will do the error.
You don't get any validaton errors when special characters are not entered because this is not what your check does:
if(specialCounter > 1)
System.out.println("Password should contain only 1 special characters");
You are printing an error message when there are more than one special characters (which doesn't make sense). I suggest:
if(specialCounter < 1)
System.out.println("Password should contain at least 1 special characters");
I am a student going into software engineering and am taking my first computer science class on coding with java. I'm struggling to get my program to apply a certain set of conditions to a String in order to print a message regarding whether or not a user's input is indeed a valid double literal.
Here are the conditions:
Consists of exactly the following characters: ’+’, ’-’, ’.’ (decimal point), and ’0’ through ’9’
Either the ’+’ or ’-’ character may appear only as the first character
The ’.’ (decimal point) character must appear exactly once
All other characters must be the ’0’ through ’9’ characters
And here is my code:
String doubleliteral;
int a;
char j;
char k;
char l;
char m;
char n;
System.out.print("Enter a valid four character double literal: ");
doubleliteral = keyboard.nextLine();
a = doubleliteral.length();
j = doubleliteral.charAt(0);
k = doubleliteral.charAt(1);
l = doubleliteral.charAt(2);
m = doubleliteral.charAt(3);
n = '.';
char i = (char)(a + 0);
if (i <= 4)
{
System.out.print("\n" + doubleliteral + " is a valid four character double literal.");
}
else if ((j == '+') || (j == '-') || (j <= 9))
{
}
else if ((k <= 9))
{
}
else if (l <=9)
{
}
else if (m <= 9)
{
}
else if ((j != '.') && (k != '.') && (l != '.') && (m != '.'))
{
System.out.print("\n" + doubleliteral + " is not a valid four character double literal.");
}
else
{
System.out.print("\n" + doubleliteral + " is not a valid four character double literal.");
}
keyboard.close();
I've been searching on the internet, in my textbook, and through my professor's presentations for about three days now trying to figure this out but nothing has come of it, please help.
Here is some psudo-code to get you in the right direction. I can't write your school answer here.
Loop through each character. Special case the first. Track if you have dot.
hasDot = false
for (i=0; i<input.length; i++) {
ch = input[i]
if (i === 0) {
validChars = [0,1,2,3,4,5,6,7,8,9,-,+,.]
// validChars must contain ch
// if ch === dot, set hasDot = true
}
else {
validChars = [0,1,2,3,4,5,6,7,8,9,.]
// validChars must contain ch
// if ch === dot and hasDot then error, else set hasDot = true
}
}
There are few conditions you need to check to figure out the validity. Let's see one by one.
+ Or -
There can be maximum one + or - operator and it has to be at the beginning of the given input.
So what you can do is, whenever you're getting a + or - operator, just check whether current index is 0 or not.
If it's not, then mark the input as invalid.
boolean isValid = true;
for(int i = 0; i < doubleliteral.length(); i++)
{
if((doubleliteral[i] == '+' || doubleliteral[i] == '-'))
{
if(i != 0)
{
isValid = false;
}
else
{
// it's valid.
}
}
}
The . (decimal point) character
There can be maximum one . character.
So you keep a count of it, check if it ever becomes more than 1.
boolean isValid = true;
int dotCounter = 0;
for(int i = 0; i < doubleliteral.length(); i++)
{
if( doubleliteral[i] == '.')
{
if(dotCounter != 0)
{
isValid = false;
}
else dotCounter++;
}
}
Check if there's any character other than digits (o to 9)
While traversing each character of the string, you can check if it's digit or not like following-
for(int i = 0; i < doubleliteral.length(); i++)
{
if(Character.isDigit(doubleliteral.charAt(i)))
{
// it's a digit
}
}
Now if we combine everything it'll look like this:
boolean isValid = true;
int dotCounter = 0;
int doubleliteralLength = doubleliteral.length();
for(int i = 0; i < doubleliteralLength; i++)
{
if((doubleliteral[i] == '+' || doubleliteral[i] == '-'))
{
if(i != 0)
{
isValid = false;
break; // we don't need to check any further
}
}
else if( doubleliteral[i] == '.')
{
if(dotCounter != 0)
{
isValid = false;
break;
}
else dotCounter++;
}
else if(Character.isDigit(doubleliteral.charAt(i)) != true)
{
// it's not a digit, not + or -, not .
isValid = false;
break;
}
}
if(doubleliteralLength == 4 && isValid)
{
System.out.print("\n" + doubleliteral + " is a valid four character double literal.");
}
else
{
System.out.print("\n" + doubleliteral + " is not a valid four character double literal.");
}
This question can be easily answered by using Regular Expressions and apply the expression to the inputted String object. Although this question is technically correct, it is not correct for the lesson your professor is teaching (which I am guessing is String parsing).
That said, here are my clues to you:
Symbols (+ or -) can only be present at character index 0.
The (decimal) ASCII values for numbers 0-9 are 48-57. Therefore, an ASCII
value outside this range that is not a "+", "-", or "." (43, 45, or
46 respectively) is an illegal character.
The next thing you need to do is write down a few combinations of characters and test them out manually. For example:
1.34 // invalid (first character must be the sign)
.123 // invalid (first character must be the sign)
-.98 // valid
-0.1 // valid
+2.3 // valid
2.+6 // invalid
4.3- // invalid
30-4 // invalid
+23. // valid (by your requirements, but it should not be)
+0.- // invalid
All of the above contain nothing but valid characters, but not all are correctly formatted. Once you test these out, you should try using other non-numeric characters.
Your code should be something like this (in psedocode)
IF STRING LENGTH > 4, ERROR (String has too many characters)
IF PERIOD COUNT > 1, ERROR // See * note
IF CHAR AT 0 NOT VALID, ERROR (Special case for symbols, period, or numbers)
IF CHAR AT X NOT VALID, ERROR (index 1-3 can only be numbers or the period)
IF CHAR AT 3 == ., ERROR (Last index cannot be the period)
PRINT STING MESSAGE
(*) My suggestion is to use a loop operation to count the number of times the period appears on the String. There are other ways to do this, but my guess is that they are not related to your current lesson. Some of those alternative methods are using regular expressions, using Streams API, using recursion, or using 3rd party libraries. Stay away from any of those solutions.
If all the tests passed, then the only thing that will be printed out will be the message containing the valid numeric string.
Last hint: Do all of the CHAR AT evaluations in a single pass (i.e. loop through your String (array of characters) to determine if the character at any given position is valid. A multiple pass solution is OK, just not elegant or effective.
The solution
import java.util.Scanner;
public class NumericStringEvaluator {
public static void main (String[] args) {
System.out.print("Enter a valid four character double literal: ");
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
scanner.close();
if (input.length() > 4) {
System.err.println("String must be exactly 4 characters");
System.exit(-1);
}
//1. Consists of exactly the following characters: ’+’, ’-’ ...
//2. Either the ’+’ or ’-’ character may appear only as the first character
if (input.charAt(0) != '+' && input.charAt(0) != '-') {
System.err.println("Invalid character at index 0: " + input.charAt(0));
System.exit(0);
}
int periodCount = 0;
for (int i = 1; i < 4; i++) {
char c = input.charAt(i);
//1. Consists of ... ’.’ ...
if (c == '.') {
periodCount++; //3. The ’.’ (decimal point) character must appear exactly once
}
// 1. Consists of ... and ’0’ through ’9’
// 4. All other characters must be the ’0’ through ’9’ characters
// ASCII values for number are 48-57 (anything outside the range is not a number)
// and the special characters have been accounted for already
else if (c < 48 || c > 57) {
System.err.println("Invalid character at index " + i + ": " + input.charAt(i));
System.exit(0);
}
}
// At this point, every character in the string has been validated (no errors found)
//3. The ’.’ (decimal point) character must appear exactly once
if (periodCount != 1) {
System.err.println("Decimal point appears more than once in numeric String.");
System.exit(0);
} else {
System.out.print("\n" + input + " is a valid four character double literal.");
}
}
}
I want to take input from User in String in which only alphabets, dot(.) and Space is allowed. If User enter any other character expect these, my program should take input from user again. It should continue this process until the user enter the right input(which i want). And at any point if user enter right input it move's further. I tried the given code but it is not working.
import java.util.Scanner;
public class TourPlanner{
public static boolean validname(String name){
String nameUp=name.toUpperCase();
for(int i=0;i<nameUp.length();i++){
char charUp=nameUp.charAt(i);
if(charUp=='A' || charUp=='B' || charUp=='C' || charUp=='D' || charUp=='E' || charUp=='F' || charUp=='G' || charUp=='H' || charUp=='I' || charUp=='J' || charUp=='K' || charUp=='L' || charUp=='M' || charUp=='N' || charUp=='O' || charUp=='P' || charUp=='Q' || charUp=='R' || charUp=='S' || charUp=='T' || charUp=='U' || charUp=='V' || charUp=='W' || charUp=='X' || charUp=='Y' || charUp=='Z' || charUp=='.' || charUp==' '){
return true;
}
}
return false;
}//valid name
public static void intro(String name, Scanner in){
validname(name);
while(validname(name)==false){
System.out.print("*** Please Enter Name Correctly ***\n");
System.out.print("What is your Name? ");
name=in.nextLine();
}
String designation;
System.out.print("Nice to meet you "+name+" Where are you travelling to? ");
designation=in.nextLine();
System.out.print("Great! "+designation+" sounds like a great trip.");
}//intro
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("**** Welcome to tour Planner ****\n");
System.out.print("What is your Name?");
String name=in.nextLine();
intro(name,in);
System.out.println("\n\n********************************************\n");
}//main
}
public static boolean validname(String name){
boolean boo = true;
String nameUp=name.toUpperCase();
for(int i=0;i<nameUp.length();i++){
char charUp=nameUp.charAt(i);
if(charUp!='A' && charUp!='B' && charUp!='C' && charUp!='D' && charUp!='E' && charUp!='F' && charUp!='G' && charUp!='H' && charUp!='I' && charUp!='J' && charUp!='K' && charUp!='L' && charUp!='M' && charUp!='N' && charUp!='O' && charUp!='P' && charUp!='Q' && charUp!='R' && charUp!='S' && charUp!='T' && charUp!='U' && charUp!='V' && charUp!='W' && charUp!='X' && charUp!='Y' && charUp!='Z' && charUp!='.' && charUp!=' '){
boo = false;
}
}
return boo;
}//valid name
once a method encounters with "return", it stops working and doesn't check other conditions. In your code, your method checks the first letter and decides that it is valid, it returns true and does not check other characters. Because of that, I modified your code and the method creates a boolean value which is initially true. And checks whether an invalid character occurs in input string. After whole loop; if not, it returns true but if it does see an invalid character, boolean value becomes false and at the end of the method, you return it after checking all characters.
Note: String library has some useful functions that allows you to check whether a char is alphabetic, numeric etc. You don't need to write all those characters into an if condition.
It keeps skipping the else part of my statement. I just want it to print out of the invalid line if all the other restrictions are not met.
import java.util.Scanner;
public class Program_3
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a password: ");
String str = input.nextLine();
boolean lowerCase = false;
boolean upperCase = false;
boolean number = false;
char y;
for (int i = 0; i < str.length(); i++)
{
y = str.charAt(i);
if(Character.isUpperCase(y))
{
upperCase = true;
}
else if(Character.isDigit(y))
{
number = true;
}
else if(Character.isLowerCase(y))
{
lowerCase = true;
}
}
if (lowerCase == true)
{
if (upperCase == true)
{
if (number == true)
{
if (str.length() >= 8)
{
System.out.println("Verdict:\t Valid");
}
}
}
}
else
System.out.println("Verdict:\t Invalid");
}
}
why does it skip and not print the invalid line when all ifs are not met?
The else in your code relates only to the outermost if.
So it will only be executed if lowerCase == false.
To fix this logic, combine all three conditions in a single if, i.e.:
if (lowerCase == true && upperCase == true && number == true && str.length() >= 8)
{
System.out.println("Verdict:\t Valid");
}
else
System.out.println("Verdict:\t Invalid");
Side note, booleans don't require explicit comparison to true, so you can write it shorter:
if (lowerCase && upperCase && number && str.length() >= 8)
The else condition is placed in the wrong place, it'll only be reached if the lowerCase condition is false. And anyway, we can simplify and combine all the ifs in a single condition, what you meant to say was this:
if (lowerCase && upperCase && number && str.length() >= 8) {
System.out.println("Verdict:\t Valid");
} else {
System.out.println("Verdict:\t Invalid");
}
This code can b be simplified to show control-flow:
if(lowerCase == true)
{
//lowerCase == true -> execute this code
if( upperCase == true)...
}else
//lowerCase == false -> execute this code
...
The inner if-statements (which are exclusive btw.) don't execute the outer else-statements, if the condition is false. The logical correct version of your code would be:
if(lowerCase && upperCase && isNumber && str.length() > 8)
System.out.println("Verdict:\t Valid");
else
...
Your test password contains at least one lowercase character. As long as it does, the else statement will never execute. To test "if all conditions are true ... else ..." try the follwing:
if (lowerCase && upperCase && number && str.length >= 8) {
// password ok
} else {
// password not ok
}
By the way, as you can see I don't use lowerCase == true since it's not needed, lowerCase already is a boolean.
I'm creating a program for my gui number converter. I want my program to ask user a binary string and if he does not enter a binary number, the program will show him error message and will ask him to enter again. The problem is that I can add restriction to alphabets but when it comes to numbers then it fails or it keeps showing the error message.
import java.util.*;
public class test {
Scanner key = new Scanner(System.in);
String in;
int b;
public test(){
do{
System.out.println("Enter the binary string of 5 numbers");
in = key.nextLine();
int i,j;
char ch;
for (i=0 ; i<=5 ; i++){
b = 0;
ch = in.charAt(i);
j = ch;
if (Character.isDigit(ch) && ch<=0 && ch>=1)
b = 1;
else
System.out.println("Please enter a binary number (1 , 0)");
break;
//b = 1;
}
}while(b != 1);
int c;
c = Integer.parseInt(in);
System.out.println("your number is: " + c );
}
public static void main (String args[]){
test obj = new test();
}
}
ch<=0 && ch>=1 does not do what you think it does. The character codes for "0" and "1" are 48 and 49, so you should check for those instead. Also, your >= comparators are backwards, but that's not really the clearest way to write this code. And since you're comparing for just those two values, Character.isDigit(ch) is redundant.
Try one of these:
ch == 48 || ch == 49
ch == '0' || ch == '1'
Scanner has an overloaded nextInt method that uses a radix
int binaryNumber = scanner.nextInt(2);
1) First logic error here for (i=0 ; i<=5 ; i++) replace i<=5 to i<5
2) change the if else condition like below
if (Character.isDigit(ch) && (ch == '0' || ch == '1'))
{
b = 1;
}
else
{
System.out.println("Please enter a binary number (1 , 0)");
break;
}