gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:59:37 25 4
gpt4 key购买 nike

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

错误代码

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com