gpt4 book ai didi

java - 阿姆斯特朗数java代码有问题

转载 作者:行者123 更新时间:2023-12-02 11:45:15 25 4
gpt4 key购买 nike

我用 java 为学校编写了一段代码,用于验证数字是否为阿姆斯特朗数字。我对其进行了编程,使其运行多次,直到用户输入 0,此时程序将终止。我有两个问题。

  1. 该代码仅在第一次运行,如果用户第一次输入 371(阿姆斯壮数字),它会运行,但之后返回该数字不是阿姆斯壮数字。

  2. 当用户输入0时,它仍然显示是否是阿姆斯特朗数的语句,这是我不希望的。

这是代码:

import java.util.Scanner; //import Scanner for user input   

public class Ch6Project {

public static void main(String[] args) {

int userNum, totalValue = 0, num, numLength; //declare variables that will be used
String suserNum; //declare user input variable
Scanner input = new Scanner(System.in); //declare a Scanner

System.out.println("Welcome to the Armstrong Number Program."); //description
System.out.println("\nTo calculate an Armstrong number: ");
System.out.println("\t 1. Cube each digit of the number.");
System.out.println("\t 2. Take the sum of these cubes.");
System.out.println("\t 3. If the sum equals the number, it is an Armstrong Number.");
System.out.println("\t e.g. 3^3 + 1^3 + 7^3 = 317");

do {
System.out.print("\nEnter a whole number (0 to quit): ");
suserNum = input.nextLine(); //collect user input
userNum = Integer.parseInt(suserNum); //parse user input
numLength = suserNum.length(); //calculate length of user input

for (int i = numLength; i > 0; i--) { //create loop to run for n times
num = Integer.parseInt(suserNum.substring(numLength - 1, numLength)); //get last digit of number
totalValue += Math.pow(num, 3); //cube a digit
numLength--; //subtract userNum by 1 to get the rest of the digits
}

if (totalValue == userNum) { //if total value equals user input, it is Armstrong #
System.out.println("Your number is an Armstrong number.");
} else { //if total value does not equal user input, it is not an Armstrong #
System.out.println("Your number is not an Armstrong number.");
}

} while (userNum != 0); //run loop until user input == 0
input.close(); //close user input

}
}

最佳答案

更改您的代码,使其在输入userNum后立即中断

例如

userNum = Integer.parseInt(suserNum); //parse user input
if (userNum == 0) {
break;
}

那么你也可以将循环更改为无限循环

while (true) {
// your code
}

关于java - 阿姆斯特朗数java代码有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48256042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com