KaiquanMah commited on
Commit
f0745b9
·
verified ·
1 Parent(s): e7d25c4

Create 11. From end to start

Browse files
Week 2: Methods, strings and lists/11. From end to start ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Write a method
2
+
3
+ String endToStart(String word)
4
+
5
+ which takes a string as its parameter.
6
+ The method constructs an inverted version of the string, where the characters of the original string are from end to beginning.
7
+
8
+
9
+
10
+
11
+ An example of calling the method:
12
+ public static void main(String[] args) {
13
+ System.out.println(endToStart("hi"));
14
+
15
+ String word = "Hellooo";
16
+ String word2 = endToStart(word);
17
+ System.out.println(word2);
18
+ }
19
+
20
+ Program outputs:
21
+ ih
22
+ ooolleH
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+ import java.util.Random;
32
+
33
+ public class Test{
34
+ public static void main(String[] args){
35
+ final Random r = new Random();
36
+
37
+ String[] words = "first second third fourth programming class method java variable".split(" ");
38
+ for (String w: words) {
39
+ System.out.println("Testing with parameter " + w);
40
+ System.out.println(endToStart(w));
41
+ System.out.println("");
42
+ }
43
+ }
44
+
45
+ public static String endToStart(String word) {
46
+ String result = "";
47
+ int wordLastIdx = word.length() - 1;
48
+ // for each word in the list
49
+ // go from wordLastIdx to 1st idx (0)
50
+ for (int i = wordLastIdx; i >= 0; i--) {
51
+ result += word.charAt(i);
52
+ }
53
+ return result;
54
+ }
55
+ }
56
+
57
+
58
+
59
+ Testing with parameter first
60
+ tsrif
61
+
62
+ Testing with parameter second
63
+ dnoces
64
+
65
+ Testing with parameter third
66
+ driht
67
+
68
+ Testing with parameter fourth
69
+ htruof
70
+
71
+ Testing with parameter programming
72
+ gnimmargorp
73
+
74
+ Testing with parameter class
75
+ ssalc
76
+
77
+ Testing with parameter method
78
+ dohtem
79
+
80
+ Testing with parameter java
81
+ avaj
82
+
83
+ Testing with parameter variable
84
+ elbairav
85
+
86
+