2

My code worked when it was in the main method, but once I try to put it in its own method, I get "args cannot be resolved to a variable" Also, I am very new to java, is there a way to simplify this code block, I have a book that shows modularized code, but it is not explained in detail.

 private static boolean validateInput() {

    //if invalid character is entered ie. a letter, will go to the catch
    try 
    {
        number1 = Integer.parseInt(args[0]);          
    }
    catch (Exception e)
    {
        System.out.println("Input #1 is not a valid integer.");
        return false;
    }

    try
    {
        number2 = Integer.parseInt(args[1]);
    }
    catch (Exception e)
    {
        System.out.println("Input #2 is not a valid integer.");
        return false;
    }

    try
    {
        number3 = Integer.parseInt(args[2]);
    }
    catch (Exception e)
    {
        System.out.println("Input #3 is not a valid integer.");
        return false;

    }
    return true;
}
4

3 回答 3

4

您可以将您的String[] args作为参数传递给validateInput().

public static void main(String[] args) {
    if (validateInput(args)) {
        ...
    }
}

private static boolean validateInput(String[] args) {
    ...
}
于 2012-10-17T03:06:12.237 回答
2

您需要将 传递args给该方法,否则它不知道它是什么。

validateInput将您的方法重新声明为

private static boolean validateInput(String[] args) {

从您的主要方法中,将其称为....

public static void main(String[] args) {
    //...Pre init...
    boolean isValid = validateInput(args);
    //...Post init...
}
于 2012-10-17T03:06:54.853 回答
0

改变

 private static boolean validateInput() { 

  private static boolean validateInput(String[] args) {

并将其main称为

     boolean result = validateInput(args);
于 2012-10-17T03:08:09.897 回答