-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCharacterInsertion.java
More file actions
85 lines (61 loc) · 2.83 KB
/
CharacterInsertion.java
File metadata and controls
85 lines (61 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String word;
int n;
String choice;
char temp; // variable to temporary store the
Scanner input = new Scanner(System.in);
System.out.println("This program is to insert an asterisk(*) at the position indexed by the user in a particular string. ");
System.out.println("Enter a string:");
word = input.next();
System.out.println("Enter the index(integer):");
n = input.nextInt();
// Changing the character with an * using the charAt method to locate
// the character at that particular location
temp = '*';
// strings are immutable thus we store each character of the string in an array so as to
// the individual characters
char[] stringArray = new char[word.length()];
for (int i=0 ; i < stringArray.length ; i++){
stringArray[i] = word.charAt(i);
if(i == n-1){
stringArray[i] = temp;
}
}
// reconverting array back to a string and storing it in the variable word.
word = new String(stringArray);
System.out.println(word);
// /*********************************************************/
// EXTRA: Replacing a * at every index that is even /
// *********************************************************/
System.out.println("Press yes or no to continue the program.");
choice = input.next();
switch (choice) {
case "yes": {
System.out.println("\tThanks for continuing to use the program");
System.out.println("\tThe program replaces an asterisk in every even index ;).");
System.out.println("Enter a string:");
word = input.next();
char[] newStringArray = new char[word.length()];
for (int i = 0; i < newStringArray.length; i++) {
newStringArray[i] = word.charAt(i);
if (i % 2 == 0) {
newStringArray[i] = temp;
}
}
word = new String(newStringArray);
System.out.println(word);
break;
}
case "no":{
System.out.println("Oops thanks for using the program. ;).");
break;
}
default:
System.out.println("Your request is invalid!\nThanks for using the Program");
break;
}
}
}