我有 3 个类文件:Bin2Dec 实现抛出异常,BinaryFormatException 是异常文件,bin2DecTest 是测试文件,用于测试 BinaryFormatException 和 bin2Dec 是否正确运行。我不知道为什么,但我无法让测试文件运行。有人请帮助我!!
测试文件:
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 文件:
//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;
}
}
二进制格式异常文件:
//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";
}
}
最佳答案
代码无法编译,因为您正在使用 conversion
,就好像它是 bin2DecTest
的方法一样。您需要使用conversion
作为Bin2Dec
的静态方法。例如
Bin2Dec.conversion(s);
另外,看看像 Junit 这样的正式测试框架和 TestNG .与滚动您自己的简单测试框架相比,它们具有一些优势,包括轻松测试抛出 Exception
的代码。
关于java - 我怎样才能让我的测试文件工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32810112/