In: Computer Science
Can you please modify where I'm going wrong (regarding Problem #2 I posted earlier; i.e., credit card validation)? Please fix my code using the general format that reflects my current level of coding/where I am in the learning process:
import java.util.Scanner;
public class AmExValidator{ public static void main(String[] args) {
Scanner amex = new Scanner(System.in);
System.out.print("Enter credit card number for validation: ");
String ccNum = amex.nextString();
//cc = credit card number as a string (not #)
//checking for cc length (15) and whether first 2 digits = 34 or 37
if (ccNum.length() != 15){
System.out.println("Invalid.");
}
else if (ccNum.substring(0, 1) == "34") || (ccNum.substring(0, 1) == "37"); //I'm receiving syntax errors here (enum, class or interface expected; as well as illegal start of expression highlighting || )
for (int i = 0; i < ccNum.length(); i++) {
char thisChar = ccNum.charAt(i); //don't want char 1, you want the value/#
int thisCharasInt = Integer.parseInt("" + thisChar);
System.out.println(thisCharAsInt);
System.out.println("Valid.");
}
}
}
else { System.out.println("Invalid.");
} //receiving error messages here too
}
}
Correct Code:
import java.util.Scanner;
public class AmExValidator{
public static void main(String[] args) {
Scanner amex = new Scanner(System.in);
System.out.print("Enter credit card number for validation: ");
String ccNum = amex.nextLine();
//cc = credit card number as a string (not #)
//checking for cc length (15) and whether first 2 digits = 34 or
37
if (ccNum.length() != 15){
System.out.println("Invalid.");
}
else if( (ccNum.substring(0, 2).equals("34")) || (ccNum.substring(0, 2).equals("37")) ){ // checking if first two characters are 37 or 34
for (int i = 0; i < ccNum.length(); i++) {
char thisChar = ccNum.charAt(i);
int thisCharasInt = Integer.parseInt("" + thisChar);
// printing each character
System.out.println(thisCharasInt);
System.out.println("Valid.");
}
}
else {
System.out.println("Invalid.");
}
}
}
Explanation: First error you are getting in else if statement is because you have not placed both conditions in one bracket because of which, if is taking first bracket condition as it condition and is not able to whatever is given after that. the second error you are getting is because you have used else statement without if statement, as you have finished the else, if ladder by putting a semicolon at the end of else if statement and placed for loop between else if and else statement.
Sample output:
Note: Let me know if you have any other doubt.