java - 平方数数学方法不起作用(默认构造函数无法处理异常类型)

标签 java

我的程序的目标是要求用户输入一个数字,然后使用创建的自定义方法计算该数字的平方并输出平方。但是,尝试这样做时出现了问题。请注意,这是我的第一个使用用户输入方法的程序(完全是初学者)

错误代码

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/

相关文章:

java - 找不到 Spring 默认登录页面

java - 限制股票期权

java - System.getProperty ("line.separator") 与 Android 的 "\n"

java - 如何在 JOGL 中解析或加载 .obj 文件?

java - 如何将数字 .00 格式化为 0.00?

java - 检查字符串是否没有任何字母而只有数字

java - Java 中类似 chroot 的环境?

java - 从组件树中读取复合组件属性的字面值

java - RecyclerView 通过 Intent extras 传递数据

java - 重新编译 Android Launcher2 (Gingerbread)