我是java的新手,我被分配了阿姆斯特朗号码。我已经创建了一个新的类ArmstrongNumber.java,我从这个网站初始化方法:http://www.programmingsimplified.com/java/source-code/java-program-armstrong-number
现在,在一个类的主方法中,我创建了另一个方法,我调用armstrong number类,现在我必须返回interval从[100到999]的armstrong number。
这就是我现在被困的地方。
public static void armtrongNumbs()
{
ArmstrongNumber returnObj = new ArmstrongNumber(); // here i m calling class.
int start = 100;
int end = 999;
for(int i = start; i<= end; i++)
{
number = i + number;
returnObj.Armstrong(number);
}
//returnObj.Armstrong();
}
为什么我的循环只返回阿姆斯特朗数?
编辑:ArmstrongNumber类
class ArmstrongNumber
{
public void Armstrong(int number)
{
int n, sum = 0, temp, remainder, digits = 0;
Scanner in = new Scanner(System.in);
System.out.println("Input a number to check if it is an Armstrong number");
n = in.nextInt();
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
System.out.println(n + " is an Armstrong number.");
else
System.out.println(n + " is not an Armstrong number.");
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
}
根据您的需求,您需要ArmstrongNumber.java
的逻辑,并根据您的需求对其进行建模。
您只需要使用以下代码,就可以停止担心使用ArmstrongNumber.java
package hello;
public class Abc {
public static void main(String[] args) {
int n, sum, temp, remainder, digits;
int start = 100;
int end = 999;
for (int i = start; i <= end; i++) {
sum = 0;
digits = 0;
temp = i;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp / 10;
}
temp = i;
while (temp != 0) {
remainder = temp % 10;
sum = sum + power(remainder, digits);
temp = temp / 10;
}
if (i == sum)
System.out.println(i + " is an Armstrong number.");
}
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p * n;
return p;
}
}
在这里你可以看到,如何将每个数字的和和数字初始化为零,然后其余的逻辑是相同的。您可以验证153、370、371,407被打印为阿姆斯特朗编号。
希望能有所帮助
try like
public int[] Armstrong(int start ,int end){
int a[],i=0;
for(int i = start; i<= end; i++)
{
number = i + number;
int n, sum = 0, temp, remainder, digits = 0;
Scanner in = new Scanner(System.in);
System.out.println("Input a number to check if it is an Armstrong number");
n = in.nextInt();
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
a[i++]=n;
else
System.out.println(n + " is not an Armstrong number.");
}
return a;
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p * n;
return p;
}
}