我需要从用户处获取一个int,将其插入公式,然后返回计算值。
我觉得我应该能够在不创建构造函数类,初始化对象,然后在该类上调用方法的情况下执行此操作,但我不知道如何操作。这里有一些代码不起作用,但到目前为止我只有这些代码。我该如何简化这个?
public class Problem1 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//Let user pick value of n
System.out.println("Please pick a value of n.");
int n=input.nextInt();
Problem1 codeTest = new Problem1();
codeTest.code(n);
}
public int code(int n) {
int sum=0;
for (int i=0; i<n; i++)
sum++;
return sum;
}
}
答案 0 :(得分:3)
因为您在main class
内部不需要实例化类本身,所以只需使用static
方法。
public static int code(int n) {
int sum=0;
for (int i=0; i<n; i++)
sum++;
return sum;
}
然后删除
Problem1 codeTest = new Problem1();
codeTest.code(n);
只需调用code()
方法
您的main method
看起来像这样
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//Let user pick value of n
System.out.println("Please pick a value of n.");
int n=input.nextInt();
code(n) or System.out.println(code(n));
}
答案 1 :(得分:1)
你应该将方法“int code(int n)”设为静态,这样main方法就可以在不实例化对象的情况下引用它,就像这样
public static int code(int n) {
//code here
}
然后在main方法中调用
System.out.println(code(n));
答案 2 :(得分:0)
你在主类中有方法代码(int n)吗?如果希望codeTest类使用该方法,则应首先创建codeTest类,然后在该类中插入code()方法。如果要将int n提交给code()并仅使用mainclass,只需删除codeTest。
public class Problem1 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//Let user pick value of n
System.out.println("Please pick a value of n.");
int n=input.nextInt();
int result = code(n);
}
public static int code(int n) {
int sum=0;
for (int i=0; i<n; i++)
sum++;
return sum;
}
}