使用者自行輸入一串數字
利用迴圈 以及遞迴 將數值做加總- [hide]import java.util.Scanner;
- public class JPD04 {
- static Scanner keyboard = new Scanner(System.in);
- public static void main(String args[]) {
- String s;
- System.out.print("Input a string of numbers: ");
- s = keyboard.nextLine();
- System.out.printf("尾端遞迴:%d\n", sumTail(s, 0));
- System.out.printf("迴圈:%d\n", sumLoop(s, 0));
- System.out.print("Input a string of numbers: ");
- s = keyboard.nextLine();
- System.out.printf("尾端遞迴:%d\n", sumTail(s, 0));
- System.out.printf("迴圈:%d\n", sumLoop(s, 0));
- }
-
-
- public static int sumLoop(String s,int r)
- {
- // 1 2 3 4
- while(!s.equals(""))
- {
- r += Integer.parseInt(s.substring(0, 1));
- s=s.substring(1);
- }
-
- return r;
-
-
- }
- public static int sumTail (String s,int r)
- {
- if(s.equals(""))
- {
- return r;
- }
- else{
- return sumTail(s.substring(1),r+Integer.parseInt(s.substring(0, 1)));
- }
- }
- }[/hide]
複製代碼 |