Question: I need to create a custom exception in Java to check for illegal characters. For example, a user is prompted to enter characters A,B, C,

I need to create a custom exception in Java to check for illegal characters. For example, a user is prompted to enter characters A,B, C, in any order and as many times but it has to be A. B, or C (upper or lower). If the User enters ADSC then we should get an exception. The problem is that this exception is bein g thrown even when the entered string meets the requirements. What am I doing wrong and how can I fix this to only throw an exception when an illegal character is entered?

import java.util.Scanner;

public class test {

public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Please enter charcters (Acceptable characters are ABC/abc in any order"); String temp = in.nextLine(); temp = temp.toUpperCase(); try { checkCharacters(temp); } catch (MastermindIllegalCharacterException e) { System.out.println("Answer is not acceptable " + e); } }

private static void checkCharacters(String str) throws MastermindIllegalCharacterException { for(int i = 0; i < str.length(); i++){ char current = str.charAt(i); if(current != 'A' || current != 'B' || current != 'C') { throw new MastermindIllegalCharacterException(" Invalid characters entered"); }else { System.out.println("Success"); } } } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!