[英]Method must return type int
I am trying to do the addition by calling a non-static method in static using dot operator. 我试图通过使用点运算符在静态中调用非静态方法来进行加法操作。 But I am getting this error: "This method must return a result of type int". 但我收到此错误:“此方法必须返回类型为int的结果”。
class Hello1 {
int pluss(int...v) {
int plus=0;
for(int x :v) {
plus=plus+x;
System.out.println(plus);
return plus;
}
}
}
public class Addition {
public static void main (String args[]) {
Hello1 h1=new Hello1();
h1.pluss(3,7,9,10);
}
}
You put the return inside the for loop! 您将返回值放入for循环中!
Change this: 更改此:
int pluss(int...v){
int plus=0;
for(int x :v)
{
plus=plus+x;
System.out.println(plus);
return plus;
}
}
To this: 对此:
int pluss(int...v){
int plus=0;
for(int x :v)
plus=plus+x;
System.out.println(plus);
return plus;
}
This is not a problem of static or non static method. 这不是静态或非静态方法的问题。 you can do it you are actually creating an object in it. 您可以做到,实际上是在其中创建一个对象。
This method must return a result of type int
means you missed the return statement at the end body of method. 表示您错过了方法末尾的return语句。
int plus(int..v){
//do whatever
//end
return plus
}
use int result = h1.pluss(3,7,9,10);
使用int result = h1.pluss(3,7,9,10);
to recieve 接收
Problem with not closing the curly braces in place, try this.. 无法合拢花括号的问题,请尝试此操作。
class Hello1 {
int pluss(int...v){
int plus=0;
for(int x :v){
plus=plus+x;
System.out.println(plus);
}
return plus;
}}
public class Addition{
public static void main(String args[]) {
Hello1 h1=new Hello1();
h1.pluss(3,7,9,10);
}}
You return
in the first iteration of your for
loop, which is probably not what you meant to do - move the return
out of it: 您在for
循环的第一次迭代中return
,这可能不是您要执行的操作-将return
移出它:
int pluss(int...v) {
int plus=0;
for (int x :v) {
plus=plus+x;
System.out.println(plus);
}
return plus;
}
The return statement should be outside the for block like this...Check out the below code, it should work fine. return语句应该在for块之外,如下所示。请检查以下代码,它应该可以正常工作。
class Hello1
{
int pluss(int... v)
{
int plus = 0;
for (int x : v)
{
plus = plus + x;
System.out.println(plus);
}
return plus;
}
}
public class Addition
{
public static void main(String args[])
{
Hello1 h1 = new Hello1();
h1.pluss(3, 7, 9, 10);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.