Data validation in Java [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Well let's just say that this used to work fine then I started it up again today and now it doesn't....
pin is 1234 and no matter what I do it says it's not valid...
and yes I know that it doesn't check the third time. I have to fix that too:
import java.util.Scanner;
import java.util.Scanner;
public class ATM
{
public ATM()
{
Scanner console = new Scanner(System.in);
final String pin = "1234";
String userPin = "";
int pinCount = 1;
boolean error = false;
do{
System.out.print("Enter PIN: ");
userPin = console.nextLine();
if (pinCount == 3) {
System.out.println("Bank account is blocked");
break;
}
else if (userPin.length() < 4 || userPin.length() > 4) {
error = true;
pinCount += 1;
}
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}
else{
System.out.println("Your PIN is incorrect");
error = true;
pinCount += 1;
}
}while(error);
}
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
}
Don't ask me why I have it split:
public class ATMtest
{
public static void main(String[] args)
{
ATM atm = new ATM();
}
}
Any help would be greatly appreciated.

You don't compare String objects with ==. You should use the equals() method. I know it does not make sense if you are new in java but == means "are they the same reference?" and equals() means "are they equal?".

userPin == pin should be userPin.equals(pin)

You declare two String variables in your code:
final String pin = "1234";
String userPin = "";
and you validate them whether they are equal to or not.
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}
String comparison should be used equals method rather than ==
Change
userPin == pin
To
userPin.equals(pin)

For digit match with exact 4 length use \d{4} regex and remove all boilerplate code on if else statement for validation.
public static boolean isNumeric(String str) {
Pattern p = Pattern.compile("\\d{4}");
Matcher matcher = p.matcher(str);
return matcher.matches();
}
For String comparison use equals method inted of == . Change it from
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
To
else if (isNumeric(userPin) && userPin.equals(pin) && pinCount < 3) {

Change this as
else if (isNumeric(userPin) && userPin == pin && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}
this
else if (isNumeric(userPin) && userPin.equals(pin) && pinCount < 3) {
System.out.println("Your PIN is correct");
break;
}

Would a switch not be better here instead of all those if conditions?

Related

Compilation Error in a very silly program

import java.util.Scanner;
public class KekOrCringe {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userGuess = "";
boolean Continue = true;
boolean ProperResponse = true;
boolean IsCorrect = true;
boolean YesNo = true;
while (Continue)
{
int secretAnswer = (int)(Math.random() * 2 + 1);
kekOrCringe(secretAnswer);
while (!IsCorrect)
{
System.out.println("Kek or Cringe?");
ProperResponse = false;
while (!ProperResponse) {
userGuess = scan.nextLine();
if (userGuess != "Kek")
System.out.println("Your entry is invalid, please try again!");
else if (userGuess != "Cringe")
System.out.println("Your entry is invalid, please try again!");
else
ProperResponse = true;
}
for (int guessCount = 0; guessCount < 1; guessCount++) {
if (userGuess = "Cringe" && userGuess != secretAnswer) {
System.out.println("It's KeK!");
guessCount++; }
else if (userGuess = "Kek" && userGuess != secretAnswer) {
System.out.println("It's CrInGe!");
guessCount++; }
else
System.out.println("Mr. Morgan, you got it right my boy!");
IsCorrect = true;
}
}
}
YesNo = false;
while(!YesNo) {
System.out.println("Would you like to play again? Yes/No");
String answer = scan.nextLine();
if (answer.equals("No")) {
Continue = false;
YesNo = true;
System.out.println("Fine. You were Cringe anyway!");
}
else if (answer.equals("Yes")) {
YesNo = true;
Continue = true;
IsCorrect = false;
}
}
}
public static String kekOrCringe(int secretAnswer) {
if (secretAnswer = 1) { return "Kek";}
if (secretAnswer = 2) { return "Cringe";}
}
}
Probably an overly complex way to do something unnecessary, but this is my first year in college learning to code, and I was asked to give this a try. I think it's funny, and will probably be funnier if it work, along with being good practice. I'm having trouble converting the int secretAnswer to a returned string, and then comparing the userGuess to the return type. Getting compilation errors on line 32 and 35. Any tips would be appreciated.
P.S. I realize it's silly. Trying to use this silly code as a learning opportunity.
Im guessing line 32 and 35 are the two ifs. userGuess != secretAnswer doesn't work since one is a String, the other an Integer. Your static method kekOrCringe(secretAnswer); returns the String you want, you just need to save it in a variable and then compare it to the userGuess.
Also please use lowercase variable names.
I can't add a comment so I am writing here.
userGuess is String but secretAnswer is int, and you are trying to check if they are equal (userGuess != secretAnswer).
You can use a new variable like secretGuess, assign kekOrCringe(secretAnswer) to secretGuess and check if userGuess is equal to secretGuess.
Like this:
String secretGuess = kekOrCringe(secretAnswer);
if (userGuess != secretGuess) {
//...
}
You are trying to compare int to string which is wrong
userGuess != secretAnswer
Also, instead of comparing you are assigning values inside if condition.
if (secretAnswer = 1) { return "Kek";}
if (secretAnswer = 2) { return "Cringe";}
It should be:
if (secretAnswer == 1) { return "Kek";}
if (secretAnswer == 2) { return "Cringe";}

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");
}

Rejecting Duplicates of Same Number

Here are the instructions for what I am supposed to be doing.
Write a program that inputs a string that represents a binary number.
The string can contain only 0s and 1s and no other characters, not
even spaces.
Validate that the entered number meets these requirements. If it does
not, display an error message. If it is a valid binary number,
determine the number of 1s that it contains. If it has exactly two 1s,
display "Accepted". Otherwise, display "Rejected".
All input and output should be from the console. Here are some sample
inputs to test:
abc 10102011 10101FF 0000 1111 (note the space in this test case)
00000000 1111 01110000001 1000001
What I have so far is written here:
import java.util.Scanner;
import java.util.Set;
class ValidateBinary1
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
boolean notCorrect = false;
for(int i = 0; i <= binary.length() - 1; i++)
{
if(binary.charAt(i) == '1')
{
isCorrect = true;
}
else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
}
}
if(isCorrect)
System.out.println("Accepted");
else if(notCorrect)
System.out.println("Rejected");
}
}
What can I write to have the program output the "rejected" line?
Try this ( you are using bitwise operator & instead of logical operator &&) but I dont think using && either is correct; you have to use bitwise or ||. Also you are not check for the number of ones, the number of ones in the input string must be exactly 2 according to your problem description.
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
short numberOfOnes = 0;
for(int i = 0; i <= binary.length() - 1; i++)
{
if(binary.charAt(i) == '1')
{
numberOfOnes++;
}
else if(! (binary.charAt(i) == '0' || binary.charAt(i) == '1'))
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
break;
}
}
if(isCorrect && numberOfOnes == 2)
System.out.println("Accepted");
else
System.out.println("Rejected");
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
boolean isCountCorrect = true;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1' || binary.charAt(i) == '0') {
continue;
} else {
isCorrect = false;
break;
}
}
if (isCorrect == true) {
int count = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
count++;
}
}
if (count > 2) {
isCountCorrect = false;
}
}
if (isCorrect = true && isCountCorrect == true) {
System.out.println("Approved");
} else
System.out.println("Rejected");
}
Here we go. I took one of the answers and used it to modify my code and came up with this:
import java.util.Scanner;
import java.util.Set;
class ValidateBinary1
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String binary = input.nextLine();
boolean isCorrect = true;
short numberOfOnes = 0;
for(int i = 0; i <= binary.length() - 1; i++)
{
if(binary.charAt(i) == '1')
{
numberOfOnes++;
}
else if(binary.charAt(i) != '0' && binary.charAt(i) != '1')
{
isCorrect = false;
System.out.println("Wrong input! Please enter a valid binary number");
}
}
if(isCorrect && numberOfOnes == 2)
System.out.println("Accepted");
else
System.out.println("Rejected");
}
}
This is exactly what I needed. Thanks!

How to go back into a while-loop, from an if statement?

Here's what i've been working on. I'm trying loop this while method, using booleans. (My teacher is incompetent, so i've been learning out of textbook.)
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
This is nested in a while loop like so ....
import java.util.Scanner; import java.lang.String;
public class booleanvariables {
public static void main (String[] args){
Scanner scn = new Scanner(System.in);
int score1, score2;
String answer, e;
boolean bothHigh, atLeastOneHigh, atLeastOneModerate, noLow, tooLow, repeat;
while (true) {
System.out.print("Enter the first test score:\t");
score1 = scn.nextInt();
System.out.print("Enter the second test score:\t");
score2 = scn.nextInt();
answer = null;
e = "n";
bothHigh = (score1 >= 90 && score2 >= 90);
atLeastOneHigh = (score1 >= 90 || score2 >= 90);
atLeastOneModerate = (score1 >= 70 || score2 >= 70);
noLow = !(score1 < 50 || score2 < 50);
tooLow = (score1 <= 50 || score2 <= 50);
repeat = (answer == "yes" || answer == "y"); //|| answer == Y || answer == Yes);
if (tooLow)
System.out.println("Inputs are too low");
if (bothHigh)
System.out.println("Qualified to be a manager");
if (atLeastOneHigh)
System.out.println("Qualified to be a supervisor");
if (atLeastOneModerate && noLow)
System.out.println("Qualified to be a clerk");
/** NESTED WRONG I'M AWARE
*/
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
}
}
}
This is much simpler than you think.
Just do it like this:
boolean stop = false;
while(!stop) {
//do whatever you want here
System.out.println("Do you want to quit?(yes or no");
String input = scan.nextLine();
if(input.equals("no")) {
stop = true;
}
}
That way, if you enter "no", it'll set the boolean to true, which then will make the condition for the while loop, !stop, equal to false.
answer == "yes"
You are checking if two objects are the same. You should use the equals method answer.equals("yes") || answer.equals("y")
Tested and Working to My Liking
I've reworked some branching. ( I use BlueJ as a compiler and it thinks this is an error without the input = scn.nextLine();
do {
//same booleans i've been using
if (!stop) {
System.out.print("Do you want to quit? (yes or no):\t");
//String input;
input = scn.nextLine();
}
//String input;
input = scn.next();
if(input.equals("yes")) {
stop = true;
System.out.println("Goodbye");
return;
}
} while (!stop);
I really don't know why blue J doesn't like it when initialize input from within the if statement

How do I validate erate to two decimal places?

When I try to use the validation methods for erate it always comes up as invalid, how do I fix the validation method using the code I used inside the method.
input = JOptionPane.showInputDialog("Enter employee hourly rate: ");
while(checkEname(input) == false)
{
input = JOptionPane.showInputDialog("Invalid! Only rate of two decimal places allowed! Re-enter employee hourly rate ");
}//end while
erate = Double.parseDouble(input);
This is the validation methods called
boolean checkErate(String input)
{
int dotCount = 0;
for(int i = 0; i < input.length(); i++)
if(input.charAt(i) == '.')
dotCount++;
else
if(!Character.isDigit(input.charAt(i)))
return false;
if(dotCount !=1 )
return false;
else
if(input.charAt(input.length() - 3) == '.')
return true;
else
return false;
}//end checkErate
There is a simpler way to check if the erate is a valid number.
Instead of doing the search for the decimal point, and evaluating it's position, what you can do instead is something like this:
String [] inputSplit = input.split(".");
if (inputSplit.length() >2) {
return false;
}
if (Pattern.matches("[a-zA-Z]+", inputSplit[0]) == false || Pattern.matches("[a-zA-Z]+", inputSplit[1]) == false){
return false;
}

Categories