我的程序的目标是要求用户输入一个数字,然后使用创建的自定义方法计算该数字的平方并输出平方。但是,尝试这样做时出现了问题。请注意,这是我的第一个使用用户输入方法的程序(完全是初学者)
错误代码
Error: Default constructor cannot handle exception type
java.io.IOException
thrown by implicit super constructor. Must define an explicit constructor
代码:
import java.io.*;
public class Squareit
{
BufferedReader myInput=new BufferedReader(new InputStreamReader(System.in));
{
String input;
int num;
System.out.println("1-12");
input = myInput.readLine();
num = Integer.parseInt(input);
}
public void square(int num)
{
int ans = (num * num);
System.out.println(" is" + ans);
}
public static void main(String[] args) throws IOException
{
Squareit t = new Squareit();
t.square(0);
}
}
最佳答案
将整个 block 移动到构造函数中,而不是作为隐式 super 构造函数。
private int num;
public SquareIt() throws IOException, NumberFormatException {
BufferedReader myInput=new BufferedReader (new InputStreamReader (System.in));
String input;
System.out.println("1-12");
input = myInput.readLine();
num = Integer.parseInt (input);
}
关于java - 平方数数学方法不起作用(默认构造函数无法处理异常类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15235535/