JAVA void空方法

如果一个方法只执行一些操作,没有最终的结果交给调用处,需使用void。
例如不用返回数值,只用打印输出。

修饰符 void 方法名称(参数类型 参数名称){
	方法体
	return 返回值;

对于没有返回值的方法,要注意:

  • 返回值并不代表不能有参数,参数和返回值没有必然联系。
public static void intsum(int a , int b){
   	System.out.println(a+b);
}
  • 不能return一个具体的返回值

  • return可以省略不写,写与不写完全等效

  • 没有返回值的方法只能单独调用,不能打印调用或者赋值调用

public class MethodVoid {
	public static void main(String[] args) {
	//		单独调用
		ten();
		helloCount(6);
	//		不能打印调用
	//		不能赋值调用
	}
	//打印输出十次helloworld
	public static void ten() {
		for(int i = 1;i<=10;i++) {
			System.out.println("helloworld!"+i);
		}
	}
	
	//	打印指定次数的helloworld
	public static void helloCount(int count) {
		for(int i = 1;i<=count;i++) {
			System.out.println("helloworld!"+i);
		}		
	}
}
发布了41 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43472877/article/details/104056579