java如何使用多个静态电源?
尝试制作一个可以使用sumDigits、reverse和isPalindrome的程序。我需要打电话给他们,测试他们。我被告知使用公共静态int-sumdights(int-n)、公共静态int-reverse(int-number)和公共静态布尔值isPalindrome(int-number)。我只是很难让这三个程序一起运行。也不知道如何打印这三个问题的答案。任何和所有的帮助都将不胜感激。老实说,我现在能做的就是x.x.我很困惑
import java.util.Scanner;
public class Project3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer");
int n = input.nextInt();
int sum = sumDigits(n);
System.out.println("The sum is " + sum);
System.out.println("The reverse is " + n);
}
public static int sumDigits(long n) {
int num = (int)(n);
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
public static int reverse(int number) {
int reverse = 0;
int rem = 0;
while (number != 0) {
rem = number % 10;
reverse = (reverse * 10) + rem;
number = number / 10;
}
return reverse;
}
public static boolean isPalindrome(int number) {
int reverse = reverse(number);
if(reverse == number) {
return true;
}
else
return false;
}
}
# 1 楼答案
要调用这三种方法,请使用main方法的名称,例如在main方法中:
我希望这有帮助
# 2 楼答案
Java有静态和非静态的方法和变量
静电干扰
在运行前定义
如果在一个类中,它在所有实例之间共享
通常用于实用函数和常量
非静态的是
在运行时之前不可定义,需要实例化
我们称之为“普通”的方法,由单个类实例使用
现在在您的例子中,因为所有的都是静态的,所以可以从静态上下文(比如main)调用它们,而无需先实例化一个类
下面是一些使用静态和非静态方法的示例代码
这会产生这个输出(来自main方法)
Extra在上面添加了代码
如何查看isPalindrome 理论上,回文是像“12321”这样的东西,两种读法都是一样的,因此检查它们需要两件事
最后请注意,OOP、值数据封装和数据完整性,这就是为什么类通常处理自己的数据,并且只提供静态方法作为实用工具