Skip to content

Instantly share code, notes, and snippets.

@peter279k
Last active May 24, 2017 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peter279k/f750851113333b98b48e0231976e105a to your computer and use it in GitHub Desktop.
Save peter279k/f750851113333b98b48e0231976e105a to your computer and use it in GitHub Desktop.
TQC+ JAVA
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