英文:
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("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;
}
}
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("Enter Number: ");
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("Enter Number: ");
number = input.nextInt();
int output = validateNumber(number);
System.out.println(output);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论