2015-09-27 3 views
1

У меня есть 3 файла класса: Bin2Dec реализует исключение, BinaryFormatException является файлом исключения, а bin2DecTest является тестовым файлом для проверки правильной работы как BinaryFormatException, так и bin2Dec. Я не знаю, почему, но я не могу запустить тестовый файл. Кто-то, пожалуйста, помогите мне!Как я могу сделать свой тестовый файл?

TEST FILE:

import java.util.Scanner; 

public class bin2DecTest { 

    public static void main(String[] args) { 
     //Convert the input string to their decimal equivalent. 
     //Open scanner for input. 
     Scanner input = new Scanner(System.in); 
     //Declare variable s. 
     String s; 

     //Prompt user to enter binary string of 0s and 1s. 
     System.out.print("Enter a binary string of 0s and 1s: "); 
     //Save input to s variable. 
     s = input.nextLine(); 
     //With the input, use try-catch blocks. 
     //Print statement if input is valid with the conversion. 
     try { 
      System.out.println("The decimal value of the binary number " + "'" + s + "'" + " is " + conversion(s)); 
      //Catch the exception if input is invalid. 
     } catch (BinaryFormatException e) { 
      //If invalid, print the error message from BinaryFormatException. 
      System.out.println(e.getMessage()); 
     } 
    } 
} 

BIN2DEC FILE:

//Prepare scanner from utility for input. 
    import java.util.Scanner; 
    public class Bin2Dec { 
        //Declare exception. 

      public static int conversion(String parameter) throws BinaryFormatException { 
      int digit = 0; 

      for (int i = 0; i < parameter.length(); i++) { 
       char wrong_number = parameter.charAt(i); 


       if (wrong_number != '1' && wrong_number != '0') { 
       throw new BinaryFormatException(""); 
       } 

       //Make an else statement and throw an exception. 

       else 
       digit = digit * 2 + parameter.charAt(i) - '0'; 
      } 
      return digit; 
      } 
     } 

BinaryFormatException FILE:

 //Define a custom exception called BinaryFormatException. 
public class BinaryFormatException extends Exception { 
    //Declare message. 

    private String message; 

    public BinaryFormatException(String msg) { 
     this.message = msg; 
    } 
    //Return this message for invalid input to Bin2Dec class. 

    public String getMessage() { 
     return "Error: This is not a binary number"; 
    } 
} 

ответ

1

код не компилировать, потому что вы используете conversion, как если бы это был метод от bin2DecTest. Вы должны использовать conversion как статический метод Bin2Dec. Например.

Bin2Dec.conversion(s); 

Кроме того, взглянуть на формальные рамки тестирования как Junit и TestNG. Они предлагают несколько преимуществ перед развертыванием собственной простой тестовой среды, включая легкое тестирование кода, который выдает Exception.

Смежные вопросы