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!

1
  • 1
    You have to initialize method local variables before using them. In your case, use input=null. Oct 16, 2014 at 13:56

3 Answers 3

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.
0

Make string input equal something to initialise it.

String input = null;
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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.