我正在尝试编写一个用于输入用户输入的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);
}
}
答案 0 :(得分:2)
当你说&#34;数字的总和&#34;时,我认为你的意思是&#34;数字的总和&#34;?
你的代码比它需要的更复杂。
// 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);