Second classroom test 1

 1 package digui;

2
3 import java.util.Scanner;
4
5 public class Digui {
6 public static void main(String args[])
7 {
8 String s;
9 Scanner sr=new Scanner(System.in);
10 System.out.println("Please enter a string" );
11 s=sr.next();
12 int i=0,j=s. length()-1;
13 int sum=0;
14 if(s.length()== 1)
15 {
16 System.out.println("String palindrome") ;
17
18 }
19 else{
20 if(di(s,i,j,sum))
21 {
22 System.out.println("String palindrome") ;
23 }
24 else
25 {
26 System.out.println("String not palindrome" );
27 }
28
29 }
30 }
31 public static boolean di(String s,int i, int j,int sum)
32 {
33
34 if(i==j&&sum%2==0&&sum!= 0)
35 {
36
37 return true;
38
39 }
40
41 if(s.charAt(i)==s.charAt(j))
42 {
43 sum+=2;
44 i++;j--;
45 }
46 else
47 return false;
48 return di(s,i,j,sum);
49 }
50 }

The purpose of the program: input a line of string and then determine whether the string is “Palindrome” is to judge whether the string is the same before and after it is read, such as “I love me”;

Program idea: Use recursive calls to solve the problem, each call traverses the string, and at the same time As with the backward traversal, the loop terminates when the subscripts indicate that i and j are the same. If there are different strings in the corresponding positions before and after in the loop, the call is exited. Finally, the function is called in the main function for judgment output.

Program perception: This test is mainly to test recursive calls. After this test, I summarized two points:

1. Recursion requires termination conditions (usually if conditional statements) Judgment);

2. Recursion needs to return to the call every time, and it can reduce the running complexity at each call.

 1 package digui;

2
3 import java.util.Scanner;
4
5 public class Digui {
6 public static void main(String args[])
7 {
8 String s;
9 Scanner sr=new Scanner(System.in);
10 System.out.println("Please enter a string" );
11 s=sr.next();
12 int i=0,j=s. length()-1;
13 int sum=0;
14 if(s.length()== 1)
15 {
16 System.out.println("String palindrome") ;
17
18 }
19 else{
20 if(di(s,i,j,sum))
21 {
22 System.out.println("String palindrome") ;
23 }
24 else
25 {
26 System.out.println("String not palindrome" );
27 }
28
29 }
30 }
31 public static boolean di(String s,int i, int j,int sum)
32 {
33
34 if(i==j&&sum%2==0&&sum!= 0)
35 {
36
37 return true;
38
39 }
40
41 if(s.charAt(i)==s.charAt(j))
42 {
43 sum+=2;
44 i++;j--;
45 }
46 else
47 return false;
48 return di(s,i,j,sum);
49 }
50 }

Leave a Comment

Your email address will not be published.