alxanderapollo alxanderapollo - 3 months ago 23
Java Question

how do i validate character input using a do while loop?

In this program i am trying to only accept A,B,C,D as character inputs from the user. Every time i get input that would pass as a valid entry such as any of the four characters, the program goes straight to the invalid message. i dont understand why that is happening, please help.

import java.util.*;

public class DLEXAM
{
public static void main(String []alex)
{
int size = 20;
char [] StudentANS = new char[size];
Scanner guebos = new Scanner(System.in);
Studentinput(StudentANS);
}


public static char [] Studentinput(char []SA)
{
Scanner guebos = new Scanner(System.in);
char singleinput = ' ';
boolean wrongAns;
for(int index = 0; index < SA.length; index++)
{
do
{
wrongAns = false;
System.out.print("please enter your answer to question #" +(index+1)+ ": ");
singleinput = guebos.nextLine().toUpperCase().charAt(0);

if(singleinput != 'A' || singleinput!= 'B' || singleinput != 'C'|| singleinput!= 'D')
{
System.out.println("Invalid Input, please RE-ENTER YOUR ANSWER");
wrongAns = true;
}

} while(wrongAns);
}

return SA;
}
}

Answer

Your ||(s) should be &&(s).

if (singleinput != 'A' && singleinput != 'B' && singleinput != 'C' 
    && singleinput != 'D')

Alternatively, applying De Morgan's laws, like

if (!(singleinput == 'A' || singleinput == 'B' || singleinput == 'C'
    || singleinput == 'D'))
Comments