gpt4 book ai didi

java - 具有求和功能的 For 循环

转载 作者:行者123 更新时间:2023-11-30 03:24:08 25 4
gpt4 key购买 nike

我正在尝试编写一个 for 循环,它将接受用户输入,无论它是正数还是负数,显示输入数字,然后显示数字之和。我可以显示数字,但我很难正确求和。

import java.util.Scanner;

public class DisplayandSum {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);

//Variable declaration
int size;
int Num1;
int count = 0; //LCV
int sum = 0; //Sum of inputs
String newNum; // Declared string for user input
System.out.println("Please enter an integers and press enter.");

newNum = input.next();

Num1 = Integer.parseInt(newNum);

size = newNum.length();

System.out.print("These are your numbers: ");

if (Num1 > 0) //If number is positive
{
for (count = 0; count <= (size - 1); count++) {
System.out.print(newNum.charAt(count) + "");
}
} else if (Num1 < 0) // If number is negative
{
System.out.print("-");

for (Num1 = 1; Num1 <= (size - 1); count++) {
System.out.print(newNum.charAt(count) + "");
}
}
if (Num1 > 0) //If positive sum
{
for (count = 0; count < (size - 1); count++) {
sum = sum + count;
}

} else if (Num1 < 0) // If negative sum
{
for (Num1 = size; Num1 > 2; Num1--) {
Num1 = Math.abs(Num1);
}
sum = sum + Num1 % 10;
Num1 = Num1 / 10;
}

sum = sum + (0 - Num1);

System.out.println("\nand the sum of your digits is: " + sum);

}
}

最佳答案

当你说“数字之和”时,我假设你实际上是指“数字之和”?

您的代码比需要的更复杂。

// Variable declaration
int sum = 0; //Sum of inputs
String newNum; // Declared string for user input

System.out.println("Please enter an integer and press enter.");
newNum = input.next();

size = newNum.length();

System.out.print("These are your numbers: ");

for (count = 0; count < size; count++)
{
char ch = newNum.charAt(count);
if (Character.isDigit(ch) {
System.out.print(ch);
sum += (ch - '0');
}
}

System.out.println("\nand the sum of your digits is: " + sum);

关于java - 具有求和功能的 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30689271/

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