2015-06-03 27 views
0

我試圖找到一種方法來增加使用charAt的值,但希望能夠在while循環內更​​新它。以下是我現有的代碼。我已經嘗試在循環內重新創建變量並將++添加到最後以增加值,但我收到意外的類型錯誤。如何增加while循環內的charAt值

我試着讓它輸入一個值(即3124)並連接每個值,然後將它們加在一起。因此,基於示例,它會給值10

public static void main(String[] args) { 

int Num, counter, i; 
String str1; 


str1 = JOptionPane.showInputDialog("Enter any number: "); 
Num = str1.length(); 

counter = 0; 
i = Integer.parseInt(Character.toString(str1.charAt(0))); 
NumTot = 0; 

while (counter <= Num) 
{ 
    NumTot = i; 
    counter++; 
    i = Integer.parseInt(Character.toString(str1.charAt(0++))); 
    } 

    System.exit(0); 
} 
+0

你可能被要求看串迭代的http:// stackoverflow.com/questions/196830/what-is-the-easiest-best-most-correct-way-to-iterate-through-the-characters-of-a – Mindeater

回答

0

一些修改程序中的一個值:

public static void main (String[] args) throws java.lang.Exception 
{ 
    int Num, counter, i; 
    String str1; 
    int NumTot = 0; 

    str1 = "3124"; 
    Num = str1.length(); 

    counter = 0; 
    while (counter < Num) 
    { 


     i = Integer.parseInt(Character.toString(str1.charAt(counter))); 
     NumTot = NumTot + i; 
     counter++; 
    } 



    System.out.println(NumTot); 
} 

Here's a working version

2

理念:

  • 取整數
  • 使用國防部10位通過提取數字

示例代碼:

public class IntegerSum { 

    public static void main(String[] args) { 

     int i = 3124; 
     int sum = 0; 
     while (i > 0) { 
      sum += i % 10; 
      i /= 10; 
     } 
     System.out.println("Sum: " + sum); 
    } 
} 

輸出:

Sum: 10 


注:我的回答是基於你的「我試圖把它帶你輸入一個值的要求(即3124)並連接每個值,然後將它們加在一起。因此,基於該例子中,將給予10」