Why is this happening on my code although I did not return any value from a method?

huangapple go评论67阅读模式
英文:

Why is this happening on my code although I did not return any value from a method?

问题

我写了一些Java代码;

int quantity = 0;

public void submitOrder(View view) {
    displayMessage(createOrderSummary());
}

public void increment(View view) {
    quantity = quantity + 1;
    display(quantity);
}

public void decrement(View view) {
    quantity = quantity - 1;
    display(quantity);
}

private String createOrderSummary() {
    String message = "数量: " + quantity;
    return message;
}

这段代码正常工作。当我在应用程序上按+和-按钮时,它会执行增加和减少方法。但在这些方法中,我使用了void。我了解到这意味着该方法没有返回值。

那么,为什么这段代码可以正常工作,显示更改后的quantity变量呢?尽管更改是在一个没有返回语句的方法中进行的。

我认为它应该显示quantity为0,因为更改后的quantity值并未从这些方法中返回。我错在哪里了?

英文:

I wrote some Java code;

int quantity = 0;

public void submitOrder(View view) {
    displayMessage(createOrderSummary());
}

public void increment(View view) {
    quantity = quantity + 1;
    display(quantity);
}

public void decrement(View view) {
    quantity = quantity - 1;
    display(quantity);
}

private String createOrderSummary() {
    String message = "Quantity : " + quantity;
    return message;
}

This code is working fine. When I press + and - buttons on app, it is executing increment and decrement methods. But in those methods, I used void. Which I learned that means "no return" on that method.

So, how can this code works as showing the quantity variable changed; although it was changed in a method which has no return statement?

I think it should show quantity as 0, because the changed quantity values were not returning from those methods. Where am I wrong?

答案1

得分: 1

实际上不返回整数并不意味着它不会应用更改(例如:递增 quantity = quantity + 1;

void 表示在调用函数的地方不会返回任何值(例如,在不同的类中调用)。但是,如果调用它,它仍然会执行其中的代码。

英文:

Actually not returning the integer doesn't mean that it's not applying the change (e.g: incrementing quantity = quantity + 1; )

void means that no value will be returned to use in the place where the function is called (for an e.g in a different class). But if you call it, it will still execute the code inside it.

huangapple
  • 本文由 发表于 2020年5月29日 04:47:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/62074266.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定