英文:
Why do I need the static keyword here?
问题
import java.util.Scanner;
public class Info {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n1, n2;
System.out.print("Enter n1: ");
n1 = input.nextInt();
System.out.print("Enter n2: ");
n2 = input.nextInt();
System.out.println(sumTotal(n1, n2));
}
public static int sumTotal(int n1sum, int n2sum) {
return n1sum + n2sum;
}
}
我不明白为什么在这里需要使用 "static"?
其他一些带有返回语句的代码不需要 "static",就像这个例子一样。那么为什么呢?
public class FirstProgram {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int age;
System.out.println("Enter your age");
age = userInput.nextInt();
var a = new FirstProgram();
a.userAge(age);
}
public int userAge(int age1) {
if (age1 < 18) {
System.out.println("You are a YOUNG!");
} else if (age1 > 18 && age1 <= 25) {
System.out.println("Young adult!");
} else {
System.out.println("Wise!");
}
return age1;
}
}
英文:
import java.util.Scanner;
public class Info {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int n1,n2;
System.out.print("Enter n1: ");
n1 = input.nextInt();
System.out.print("Enter n2: ");
n2 = input.nextInt();
System.out.println(sumTotal(n1,n2));
}
public static int sumTotal(int n1sum, int n2sum) { // *why static includes here*
return n1sum+n2sum;
}
}
I don't understand why do I need to put static in here?
Some other codes with return statement doesn't need static, like this one. So why?
public class FirstProgram {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in); // for scanning
int age;
System.out.println("Enter your age");
age = userInput.nextInt();
var a = new FirstProgram();
a.userAge(age);
}
public int userAge(int age1)
{
if ( age1 < 18 )
{
System.out.println("You are a YOUNG!");
}
else if (age1 > 18 && age1 <=25)
{
System.out.println("Young adult! ");
}
else
{
System.out.println("Wise!");
}
return age1;
}
}
答案1
得分: 1
我不明白为什么我需要在这里加入 static。
Java 不允许直接从静态方法调用非静态方法。
有些其他带有 return 语句的代码不需要 static,就像这个例子。那么为什么?
这是 Java 允许你从静态方法中调用非静态方法的方式(即使用类的实例)。
在这里了解更多关于 static
关键字的信息。
英文:
> I don't understand why do I need to put static in here.
Java does not allow calling non-static
method from a static
method directly.
> Some other codes with return statement doesn't need static, like this
> one. so whyy?
This is how (i.e. using the instance of the class) Java allows you to call a non-static
method from a static
method.
Learn more about static
keyword here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论