1
我正在嘗試編寫一個for循環,它將採取用戶輸入,無論是正數還是負數,顯示輸入數字,然後顯示數字總和。我可以儘可能地顯示數字,但我很難得到正確的總結。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);
}
}
不錯的方法,但你也可以使用一些簡化。嚴重嗎?<=尺寸-1「? – CandiedOrange
是的。沒有看那個。正在專注於循環內臟。定影。 –