Last active
May 24, 2017 16:29
-
-
Save peter279k/f750851113333b98b48e0231976e105a to your computer and use it in GitHub Desktop.
TQC+ JAVA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class JPA03 { | |
static Scanner keyboard = new Scanner(System.in); | |
public static void main(String[] args) { | |
int sum = 0; | |
boolean check = false; | |
System.out.print("Input a string of numbers: "); | |
String str = keyboard.nextLine(); | |
try { | |
Integer.parseInt(str); | |
} catch(Exception e) { | |
check = true; | |
} | |
if(!check) { | |
System.out.println("尾端遞迴:" + sumR(str, sum)); | |
System.out.println("迴圈:" + sumLoop(str)); | |
} else { | |
System.out.println("尾端遞迴:" + sum); | |
System.out.println("迴圈:" + sum); | |
} | |
System.out.print("Input a string of numbers: "); | |
str = keyboard.nextLine(); | |
try { | |
Integer.parseInt(str); | |
} catch(Exception e) { | |
check = true; | |
} | |
if(!check) { | |
System.out.println("尾端遞迴:" + sumR(str, sum)); | |
System.out.println("迴圈:" + sumLoop(str)); | |
} else { | |
System.out.println("尾端遞迴:" + sum); | |
System.out.println("迴圈:" + sum); | |
} | |
} | |
public static int sumR(String str, int sum) { | |
if(str.equals("")) { | |
return sum; | |
} | |
return sumR(str.substring(1), sum + Integer.parseInt(str.substring(0, 1))); | |
} | |
public static int sumLoop(String str) { | |
int sum = 0; | |
for(int index=0;index<str.length();index++) { | |
sum += Integer.parseInt(String.valueOf(str.charAt(index))); | |
} | |
return sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment