Question

I need help with this java code. I need to validate the input from the user...

I need help with this java code.

I need to validate the input from the user to include entries in the fields, that customer id is an integer and that the credit card number is valid. It must start with a 4, 5, or 6 and must be in the format xxxx-xxxx-xxxx-xxxx. Otherwise, you must tell the user that it is invalid and let him try to enter the number.

Please do not use Regex on this question.

However this is a java program.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Java Code below:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
*
* @author saurabh
*/
public class Card {
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Card Number: ");
String cn = br.readLine();
int n = cn.length();
int flag = 0;
if(n==16 || n==19){
char[] c = cn.toCharArray();
int num = (int)c[0]-(int)'0';
if(num!=4 && num!=5 && num!=6){
System.out.println("Card number must start with 4, 5 or 6.");
flag = 1;
}
if(n==16){
for(int i=0;i<16;i++){
num = (int)c[i]-(int)'0';
if(num>=0 && num<=9){
//do nothing
}
else{
System.out.println("Invalid Input");
flag = 1;
break;
}
}
}
else{
for(int i=0;i<19;i++){
if((i==4 || i==9 || i==14)&& c[i]!='-'){
System.out.println("Invalid Input ");
flag = 1;
break;
}
else{
if(i==4 || i==9 || i==14)
continue;
num = (int)c[i]-(int)'0';
if(!(num>=0 && num<=9)){
System.out.println("Invalid Input");
flag = 1;
break;
}
}
}
}
if(flag==0)
System.out.println("Correct Input!!!");
}
else{
System.out.println("Invalid Input");
}
}
}

Output:

The code was written and tested in NetBeans IDE 8.2.

Please like,

:-)

Thank you for your support.

Add a comment
Know the answer?
Add Answer to:
I need help with this java code. I need to validate the input from the user...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT