0

After the user enters a 2 digit hexadecimal the program will continue unless they enter a 1 digit or 3-digit and more hexadecimal, I want the user to try again however after the first "invalid" message in the console when the user enters an incorrect value for the second time it goes through and is not stopped by an "invalid" message.

import java.util.Scanner;

public class Dance6 {
    public static void main(final String[] args) {
        Scanner sc = new Scanner(System.in);
        String hexadecimal;
        System.out.println("Please enter a 2-digit hexadecimal value : ");
        hexadecimal = sc.nextLine();

        if (hexadecimal.length() != 2) {
            System.out.println("Invalid input, please try again : ");
            sc.next();
        }
    }
}
Samuel Philipp
  • 9,552
  • 12
  • 27
  • 45
Vamsi
  • 5
  • 3

2 Answers2

0

This if statement:

 if (hexadecimal.length() != 2) {
   System.out.println("Invalid input, please try again : ");
   sc.next();
 }

is executed only once.
You need a loop that validates over and over the input until it is valid:

 while (hexadecimal.length() != 2) {
     System.out.println("Invalid input, please try again : ");
     hexadecimal = sc.nextLine();
 }
forpas
  • 117,400
  • 9
  • 23
  • 54
0

You should use a loop for this. Let the user try again until he enters a valid String:

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a 2-digit hexadecimal value : ");
String hexadecimal = sc.nextLine();
while (hexadecimal.length() != 2) {
    System.out.println("Invalid input, please try again: ");
    hexadecimal = sc.nextLine();
}
System.out.println("You entered: " + hexadecimal);
Samuel Philipp
  • 9,552
  • 12
  • 27
  • 45