2015-06-07 131 views
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); 

    } 
} 

回答

2

當你說「數字之和」時,我假設你實際上是指「數字之和」?

你的代碼比需要的更復雜。

// 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); 
+0

不錯的方法,但你也可以使用一些簡化。嚴重嗎?<=尺寸-1「? – CandiedOrange

+0

是的。沒有看那個。正在專注於循環內臟。定影。 –