java 如何在java中创建没有参数的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27027104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create a method without parameters in java?
提问by Bogdan
I've been trying to write some code in java and I have some lines that I write in a lot of places(exactly the same). I want to replace those lines everywhere with a method. Is that possible ?
我一直在尝试用 java 编写一些代码,并且我在很多地方都写了一些行(完全相同)。我想用一种方法替换所有地方的那些行。那可能吗 ?
For example
例如
public fill()
{ x=x+1;
if( x == sizeX){
y=y-1;
x=0;
}
}
Those variables x,y,size are defined outside the method. I also tried with public void , void and a lot of other combinations that I could find. Is it possible what I am trying to do in java ?
这些变量 x,y,size 在方法之外定义。我还尝试了 public void 、 void 和我能找到的许多其他组合。我在 java 中尝试做的事情有可能吗?
回答by Salih Erikci
public class Test{
private int x, y, sizeX;
public void fill(){
x=x+1;
if( x == sizeX){
y=y-1;
x=0;
}
}
}
回答by Pier-Alexandre Bouchard
From JLS §8.4.5:
来自 JLS §8.4.5:
The result of a method declaration either declares the type of value that the method returns (the return type), or uses the keyword void to indicate that the method does not return a value.
方法声明的结果要么声明该方法返回的值的类型(返回类型),要么使用关键字 void 指示该方法不返回值。
You forgot the return type of your method. Since your method does not return a value, the return type should be void
.
您忘记了方法的返回类型。由于您的方法不返回值,因此返回类型应为void
.
Also, this method should be in a class with fields.
此外,这个方法应该在一个有字段的类中。
public class Foo{
private int x;
private int y;
private int sizeX;
public void fill(){
x=x+1;
if( x == sizeX){
y=y-1;
x=0;
}
}
}
回答by Osy
HTH
HTH
public class TestMethod {
static int x, y , sizeX;
public static void main(String[] args) {
x = 9;
y = 200;
sizeX = 10;
System.out.println("x/y/sizex :" + x + "/" + y + "/" + sizeX);
fill();
System.out.println("x/y/sizex :" + x + "/" + y + "/" + sizeX);
}
static void fill(){
x=x+1;
if( x == sizeX){
y=y-1;
x=0;
}
}
}