2015-06-07 88 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

是的。没有看那个。正在专注于循环内脏。定影。 –