java - Java - Why void when I'm storing value in variable
问题描述
So, the question is. If I'm calling method guess from class - Player
and it is a void-type method without return statement in it, how come I'm able to store result of number = (int)(Math.random() * 10)
in number
variable for 3 different objects (p1, p2, p3)
?
I'm little confused about when should I use return statement or void-type methods, because if number = (int)(Math.random() * 10)
is giving some results which I want to use, why then I don't need to return this results from a method to pass them to the number
variable which I declared in int number = 0;
public class Player {
int number = 0;
public void guess() {
number = (int)(Math.random() * 10);
System.out.println("I'm guessing " + number);
}
}
解决方案
A void
method does not return anything, but it still allows you to do things. (Print to the console, modify variables etc) The void
keyword just means that it doesn't return a value. (In void
methods you can still use a blank return;
to end the method) And because you are modifying your number
variable in the GuessGame
object the changes you make will stay even though you don't return a variable. Try this simple test to see what I mean:
//In your GuessGame class
int number = 0;
public void foo() {
number++;
}
public static void main(String[] args) {
GuessGames games = new GuessGames();
games.foo();
System.out.println(games.number);
//Outputs 1
}
docs for the return
statement
推荐阅读
- .net - How to host .net core microservices on IIS server
- google-sheets - Google sheets use a filter on date and category in one go
- postman - Encoding automatically in Postman
- patch - Which means distributing a modified program as patches?
- c - Is there a way that I can go up an ADT list? (bubblesorting an ADT list)
- c++ - Why did STL made a(nother) distinction between a std::array and a std::initializer_list
- java - Java - app crash when using in app purchase
- jquery - 使用自动完成功能在 Jquery 中发送请求并获得响应?
- c++ - 如何为模板函数重载 []
- python - 使用 python 发送电子邮件 - 未经授权的发件人地址