更改影响主函数中变量的方法中的值

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

Changing values in method that affect variables in main

问题

我正在尝试创建一个验证数字的代码。如果数字小于10或大于20,则数字的值将更改为15。

以下是代码:

public class test {

    public static void main(String[] args) {
        int number;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter Number: ");
        number = input.nextInt();
        validateNumber(number);
        System.out.println(number);

    }

    public static int validateNumber(int number) {
        if (number < 10 || number > 20) {
            number = 15;
        }
        return number;
    }
}

在主方法中,方法中的更改并未产生任何效果。

英文:

I am trying to create code that validates a number. If the number is lower than 10 or higher than 20, the value of the number will be changed to 15.

Here is the code:

public class test {

    public static void main(String[] args) {
        int number;
        Scanner input = new Scanner(System.in);
        System.out.print(&quot;Enter Number: &quot;);
        number = input.nextInt();
        validateNumber(number);
        System.out.println(number);

    }

    public static int validateNumber(int number) {
        if (number &lt; 10 || number &gt; 20) {
            number = 15;
        }
        return number;
    }
}

The change in the method doesn't do anything in the main method.

答案1

得分: 1

容易极了,日本风格!

number = validateNumber(number);

英文:

easy-peasy, japanesey!

number = validateNumber(number);

答案2

得分: 1

你已经返回一个整数。
所以只需执行:

number = validateNumber(number);

这样它将用函数的返回值覆盖 number

英文:

You already return an Integer.
so just do:

number = validateNumber(number);

Thus it will override the number with the return value of the function.

答案3

得分: 0

你有两种方式来做这个:

1. 使用函数调用直接打印:

int number;
    Scanner input = new Scanner(System.in);
    System.out.print("输入数字:");
    number = input.nextInt();
    System.out.println(validateNumber(number));

2. 存储在变量中,然后使用它:

int number;
    Scanner input = new Scanner(System.in);
    System.out.print("输入数字:");
    number = input.nextInt();
    
    int output = validateNumber(number);
    System.out.println(output);
英文:

You have two ways to do this:

1. Direct printing with function call :

int number;
    Scanner input = new Scanner(System.in);
    System.out.print(&quot;Enter Number: &quot;);
    number = input.nextInt();
    System.out.println(validateNumber(number));

2. Storage in a variable, then using it:

int number;
    Scanner input = new Scanner(System.in);
    System.out.print(&quot;Enter Number: &quot;);
    number = input.nextInt();
    
    int output = validateNumber(number);
    System.out.println(output);

huangapple
  • 本文由 发表于 2020年10月23日 17:22:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64497356.html
匿名

发表评论

匿名网友

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

确定