0

New to the site and plan to use it a lot since I am in school for computer science. Im trying to do an error check in java on making sure a hex is enter however im being told that the string input isnt intialized.

Scanner keyboard = new Scanner(System.in);



String input;


Pattern legalInput = Pattern.compile("a-fA-F0-9");
Matcher match = legalInput.matcher(input);
boolean answer = match.find();
int counterA = 0;
while (counterA < 1) {
    System.out.print("Please enter a hex number:");
    input = keyboard.nextLine();
    int counter = 0;
    while (counter < 1) {

        if (answer == true )
            counter++;
        else System.out.println("Error");
        } counterA++;
    }

Since this is my first programming language im learning in so lost any and all help is apperciated!

jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
jscincy1
  • 29
  • 1
  • 9

3 Answers3

0

You can't assign Matcher with input you don't have yet.

String input;
Pattern legalInput = Pattern.compile("a-fA-F0-9");
// Matcher match = legalInput.matcher(input); // <-- input isn't set yet.

Move it into your while loop, just after you assign input -

input = keyboard.nextLine();
Matcher match = legalInput.matcher(input); // <-- now input is set.
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Make string input equal something to initialise it.

String input = null;
Moob
  • 14,420
  • 1
  • 34
  • 47
0

Always initialize your variables, go through this link

in your case initialize input as null or your default value.

for example:

 String input=null;

Addition to this try to close the resource as it will create a Resource leak

 keyboard.close();
Community
  • 1
  • 1
Imran
  • 429
  • 9
  • 23