调用方法来检查输入错误

时间:2016-02-15 07:52:47

标签: java exception-handling try-catch

我在名为PersonalContact的类中使用此方法。

public void validate(String name, int age, String address, String city, String state, String zip){

     //If the name field is the empty string or null, then throw a NullPointerException.
    if (name.equals(null)){
        throw new NullPointerException();
    }
    //If the age field is not between 1-100, then throw an IllegalStateException
    if (age < 1 || age > 100){
        throw new IllegalStateException();
    }
    //If the address or city field is the empty string or null, then throw a NullPointerException.
        if(address.equals(null) || city.equals(null)){
            throw new NullPointerException();
        }
    //If the state field is not exactly 2 characters, then throw an IllegalStateException
        if (state.length() != 2){
            throw new IllegalStateException();
        }
    //If the zip code field is not exactly 5 numeric characters, then throw an IllegalStateException
        if (zip.length() != 5){
            throw new IllegalStateException();
        }

    }

@Override
public void validate(String name, int age ) {


}

我试图在驱动程序中调用该方法:

import java.util.Scanner;

public class PlannerMain {
 static Scanner scanner = new Scanner(System.in);

 public static void main(String[] args) {

   while (true) {

    System.out.println("Create new contact?");
    System.out.println("1.Personal contact ");
    System.out.println("2.Business Contact ");
    System.out.println("3.Exit.");

    int option = scanner.nextInt();
    boolean pcLoop = true;

    if (option == 1) { // Create Personal Contact

     do {
      try {
       validate();

       System.out.println("Name?(No spaces)");
       String name = scanner.next();

       System.out.println("Age?");
       int age = scanner.nextInt();

       System.out.println("Address?(No Spaces)");
       String address = scanner.next();

       System.out.println("City?");
       String city = scanner.next();

       System.out.println("State?");
       String state = scanner.next();

       System.out.println("Zip");
       String zip = scanner.next();

       PersonalContact pc = new PersonalContact(name, age, address, city, state, zip);
       System.out.println(pc.toString()); // Prints out the
       // contact info
       pcLoop = false; // Ends the loop and goes back to the
       // menu
      } catch (Exception age) {
       System.out.println("Please enter name without spaces.");
      }

     } while (pcLoop); // Ends option 1

    } // End option 1
    else if (option == 2) { // Create Business Contact

     System.out.println("Name?(No spaces)");
     String name = scanner.next();

     System.out.println("Age?");
     int age = scanner.nextInt();

     System.out.println("Business Phone?");
     String businessPhone = scanner.next();

     System.out.println("Cellphone?");
     String cellPhone = scanner.next();

     BusinessContact bc = new BusinessContact(name, age, businessPhone, cellPhone);

     System.out.println(bc.toString());

    } // End option 2
    else if (option == 3) { /** Terminates the program */
     System.exit(0);
    } // End option 3
   } // End while

  } // End void main
} // End

我希望该方法与try-catch块一起使用,以捕获PersonalContact中各个字段的不适当的用户输入。我想为我的BusinessContact做同样的事情。我知道我应该在try块中调用该方法,但我不明白为什么它没有从PersonalContact类中调用它而我不明白例外如何用这种方法处理。

2 个答案:

答案 0 :(得分:1)

正如其他人所述,您尚未实例化您的对象,因此您无法对尚不存在的内容调用validate。 我也想提出一个建议。为什么不尝试在每个setter方法中放置所有这些验证。然后,您可以从PersonalContact的构造函数中调用它们。例如,在PersonalContact类中:

private String name;
private int age;
...

//This should throw all the types of exceptions
//It should look like public PersonalContact(...){ throws NullPointerException, IllegalStateException , etc.
public PersonalContact(name, age, address, city, state, zip){
    setName(name);
    setAge(age);
    ...
} 

public void setName(String name) throws NullPointerException {
    //If the name field is the empty string or null, then throw a NullPointerException.
    if (name == null || name.isEmpty()){
        throw new NullPointerException();
    }
    this.name = name;
}

public void setAge(int Age) throws IllegalStateException {
    //If the age field is not between 1-100, then throw an IllegalStateException
    if (age < 1 || age > 100){
        throw new IllegalArgumentException(); //as someone in the comments mentioned, use this instead of IllegalStateException
    }
    this.age = age;
}
...

您可以继续为所有其他方法执行这些操作,并通过从构造函数中调用它,它将在您创建对象时验证字段。

答案 1 :(得分:0)

在拥有实例之前,您无法调用实例方法。你需要打电话。

PersonalContact pc = new PersonalContact(name, age, address, city, state, zip);
pc.validate();

然后您不需要传递验证任何参数,因为它们是pc状态的一部分。验证看起来应该更像这样。

public void validate() {
     //If the name field is the empty string or null, then throw a NullPointerException.
    if (this.name == null || this.name.equals("")){
        throw new NullPointerException();
    }
    //If the age field is not between 1-100, then throw an IllegalStateException
    if (this.age < 1 || this.age > 100){
        throw new IllegalStateException();
    }
    //If the address or city field is the empty string or null, then throw a NullPointerException.
        if(this.address == null || this.city == null){
            throw new NullPointerException();
        }
    //If the state field is not exactly 2 characters, then throw an IllegalStateException
        if (this.state.length() != 2){
            throw new IllegalStateException();
        }
    //If the zip code field is not exactly 5 numeric characters, then throw an IllegalStateException
        if (this.zip.length() != 5){
            throw new IllegalStateException();
        }
}

请注意myString.equals(null)不起作用。你必须使用myString == null。虽然如果你从键盘输入输入,你更可能有一个空字符串而不是一个空字符串,所以使用myString.equals(“”)。

如果你真的想在没有实例化PersonalContact的情况下调用validate方法,你需要将第一个validate方法设为静态并将其称为

PersonalContact.validate(name, age, address, city, state, zip);

我建议一般地阅读有关面向对象编程的一些内容,因为你似乎没有完全掌握它。

相关问题