检查输入错误时,变量未初始化

时间:2014-10-16 13:55:30

标签: java initialization

该网站的新手,并计划在我上学计算机科学时使用它。我试图在java中进行错误检查以确保输入十六进制但是我被告知字符串输入不是初始化。

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++;
    }

因为这是我的第一个编程语言,所以我在学习中失去了所有的帮助,所有的帮助都得到了帮助!

3 个答案:

答案 0 :(得分:0)

您无法为Matcher分配您尚未提供的输入。

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

在您指定while -

后立即将其移至input循环
input = keyboard.nextLine();
Matcher match = legalInput.matcher(input); // <-- now input is set.

答案 1 :(得分:0)

使字符串input等于初始化它。

String input = null;

答案 2 :(得分:0)

始终初始化您的变量,请完成此link

在您的情况下,将输入初始化为null或您的默认值。

例如:

 String input=null;

除此之外,请尝试关闭资源,因为它会创建Resource leak

 keyboard.close();
相关问题