[!INDEX]
- find digit , alphabet and character isDigigt(), isAlphabet(), Character
- encrypt message with given key, StringBuilder(), subtring(), read()
- encrypt the message with proper case, read(), append(),substring,
- encrypt and decrypt with two key , using string using external file
- check input character is vowel or not
- replace the string vowel with specific characters
- replace vowels with two different character present at even and odd place
- replace given character with even odd position 3 parameters
- simple dice , Random() mt, for 2 and 12
- simple dice , Random() mt, for all combinations
- roll a dice and save the value in array make code shorter
- read words from a file and save it in the array
- count number of words appear in the shakespera story form a list
1. find digit , alphabet and character isDigigt(), isAlphabet(), Character
// find digit , alphabet and character in a string
// isDigigt(), isAlphabet(), Character, multiple variable return
public class Cipper01 {
public static void main(String [] args){
Cipper01 cp1 = new Cipper01();
String s = cp1.testString("ABCabc0123456789';#!");
System.out.println(s);
}
String testString(String x){
int a = 0;
int b = 0;
int c = 0;
for(int i =0;i<x.length();i++){
char ch = x.charAt(i);
if(Character.isDigit(ch)){
System.out.println(ch+" is digit ");
a=a+1;
}
if(Character.isAlphabetic(ch)){
System.out.println(ch+" is alphabetic ");
b=b+1;
}
if(ch=='#'){
System.out.println(ch+" is hashtag");
c=c+1;
}
}
return "Digigt are = "+a+ " ,Alphabetic are = "+b+" , Hashtag are = "+c+" . " ;
}
}
2. encrypt message with given key, StringBuilder(), subtring(), read()
// encrypt message with given key
// StringBuilder(), subtring(), read()
import java.io.FileInputStream;
import java.io.IOException;
public class CeaserCipher2 {
public static void main(String[] args) {
int key = 17;
String filePath = "C:/Users/rajat/Desktop/message1.txt";
try (FileInputStream fis = new FileInputStream(filePath)) { // Using try-with-resources
StringBuilder message = new StringBuilder();
int x;
while ((x = fis.read()) != -1) {
message.append((char) x);
}
// Initialize encryption process
StringBuilder encrypted = new StringBuilder(message);
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String shiftedAlphabet = alphabet.substring(key) + alphabet.substring(0, key);
for (int i = 0; i < encrypted.length(); i++) {
char currChar = Character.toUpperCase(encrypted.charAt(i)); // Convert to uppercase
int idx = alphabet.indexOf(currChar);
if (idx != -1) { // Only shift alphabetic characters
char newChar = shiftedAlphabet.charAt(idx);
encrypted.setCharAt(i, newChar);
}
}
// Output the original and encrypted messages
System.out.println("Original Message: " + message.toString());
System.out.println("Encrypted Message: " + encrypted.toString());
} catch (IOException e) {
System.out.println("File not found or an error occurred while reading the file.");
e.printStackTrace();
}
}
}
// 1. Open file and append it in stringbuilder file.
// 2. Make alpha String AS.
// 3. Make shifted string using key SS.
// 4. Read first char, Make it Uppercase.
// 5. Search it in the AS indexOF and find it in SS using charAt.
// 6. if found setCharAt in stringbuilder
3. encrypt the message with proper case, read(), append(),substring,
// encrypt the message with proper case, read(), append(),substring,
import java.io.FileInputStream;
public class CeaserCipher3 {
FileInputStream fr;
StringBuilder sb1;
public static void main(String [] args){
CeaserCipher3 cc = new CeaserCipher3();
cc.testBlock();
}
void testBlock(){
String x1 = testCaesar();
System.out.println(x1);
}
String testCaesar() {
int key = 17;
String path = "C:/Users/rajat/Desktop/message2.txt";
try {
fr = new FileInputStream(path);
sb1 = new StringBuilder();
int x =0;
while((x= fr.read())!= -1){
sb1.append((char)x);
}
} catch (Exception e) {
System.out.println("file not found . exception mgs is : * * * "+e);
}
StringBuilder secreatMsg = new StringBuilder(sb1);
String stringOriginalUP = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String stringOriginalLO = "abcdefghijklmnopqrstuvwxyz";
// shift the string with key
String stringShiftedUP = stringOriginalUP.substring(key)+stringOriginalUP.substring(0, key);
String stringShiftedLO = stringOriginalLO.substring(key)+stringOriginalLO.substring(0, key);
//find index of secreat message first char in stringOriginalUP and stringOriginalLO
for(int i=0;i<secreatMsg.length();i++){
char charPos = secreatMsg.charAt(i);
int indexUP = stringOriginalUP.indexOf(charPos);
int indexLO = stringOriginalLO.indexOf(charPos);
//find char at found index and set it with the original secrete message
if(indexUP!=-1){
char pos = stringShiftedUP.charAt(indexUP);
secreatMsg.setCharAt(i, pos);
}
if(indexLO!=-1){
char pos = stringShiftedLO.charAt(indexLO);
secreatMsg.setCharAt(i, pos);
}
}
String encryptedMsg = secreatMsg.toString();
return encryptedMsg;
}
}
4. encrypt /decrypt the message using two key
// encrypt /decrypt the message using two key
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Cipher04 {
public static void main(String [] args ){
Cipher04 c04 = new Cipher04();
// c04.testCaesar();// test using string
c04.testCaesarfile();// test using external file
}
public String encrypt(String input, int key1, int key2) {
StringBuilder encrypted = new StringBuilder(input);
String upperAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lowerAlphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i=0;i<input.length();i++){
char charAtPos = input.charAt(i);
int resultEven = (i+1)%2;
if(resultEven ==0){
newChar(key1, upperAlphabet, lowerAlphabet, charAtPos, encrypted, i );
}
else{
newChar(key2, upperAlphabet, lowerAlphabet, charAtPos, encrypted, i );
}
}
return encrypted.toString();
}
// test the method for above
void testCaesar() {
// test for encrypt
int key1 = 21;
int key2 = 8;
String message ="At noon be in the conference room with your hat on for a surprise party. YELL LOUD!";
// test for decrypt
// int dekey1 = 21;
// int dekey2 = 8;
// int key1 = (26- dekey1);
// int key2 = (26- dekey2);
// String message ="Io iwjv jz dv bcm kjvammmikz mwju edbc twpz pvb wi awm v ncmxmqnm xvzog. TMGT TJCY!";
String encrypted = encrypt(message, key1,key2);
System.out.println("Encrypted: " + encrypted);
}
// test using external file
void testCaesarfile() {
StringBuilder message = new StringBuilder();
// Read file content and build the message
try (BufferedReader rd = new BufferedReader(new FileReader("data/fileencrypt.txt"))) {
String line;
while ((line = rd.readLine()) != null) {
message.append(line).append("\n"); // Append each line and add newline if needed
}
} catch (IOException e) {
e.printStackTrace();
}
// keys and string for encrypt
// int key1 = 21;
// int key2 = 8;
// keys and string for decrypt
int dekey1 = 21;
int dekey2 = 8;
int key1 = (26- dekey1);
int key2 = (26- dekey2);
// Perform encryption
String encrypted = encrypt(message.toString().trim(), key1, key2);
System.out.println("Encrypted: " + encrypted);
}
// check even odd and then convet it to accordingly
String newChar(int key, String upperAlphabet, String lowerAlphabet, char charAtPos, StringBuilder encrypted, int i ){
String shiftupperAlpa1 = upperAlphabet.substring(key) + upperAlphabet.substring(0, key);
String shiftlowerAlpa1 = lowerAlphabet.substring(key) + lowerAlphabet.substring(0, key);
int idx = upperAlphabet.indexOf(charAtPos);
if (idx != -1) {
char newChar = shiftupperAlpa1.charAt(idx);
encrypted.setCharAt(i, newChar);
} else {
// Check if the character is lowercase
idx = lowerAlphabet.indexOf(charAtPos);
if (idx != -1) {
char newChar = shiftlowerAlpa1.charAt(idx);
encrypted.setCharAt(i, newChar);
}
}
return encrypted.toString();
}
}
// 1. store secrete message in string SM ;
// 2. star loop and find first charpos index which is 0 ( make it =0+1), coz given that forst pos is 1
// 3. if it is odd encrypt it key 1 else key2
// 4. make original alphabet string = OS
// 5. make shift alphabet string = SA
// 6. find index in original alpha and charAt in shifted alpha.
// 7. for decrypte use the above with 26-key.
5. check input character is vowel or not
// check input charcter is vowel or not
public class VowelCheck4 {
public static void main(String [] args){
VowelCheck4 vc = new VowelCheck4();
vc.checkVowel('e');
vc.testCode(); // use for testing
}
String checkVowel(char ch){
String vowelList = "AEIOU";
char ch1 = Character.toUpperCase(ch);
int x = vowelList.indexOf(ch1);
if(x!=-1){
return "true";
}
else{
return "false";
}
}
void testCode(){
VowelCheck4 vc = new VowelCheck4();
if(vc.checkVowel('a')!= "true")System.out.println("error in code");
if(vc.checkVowel('e')!= "true")System.out.println("error in code");
if(vc.checkVowel('i')!= "true")System.out.println("error in code");
if(vc.checkVowel('o')!= "true")System.out.println("error in code");
if(vc.checkVowel('u')!= "true")System.out.println("error in code");
if(vc.checkVowel('A')!= "true")System.out.println("error in code");
if(vc.checkVowel('E')!= "true")System.out.println("error in code");
if(vc.checkVowel('I')!= "true")System.out.println("error in code");
if(vc.checkVowel('O')!= "true")System.out.println("error in code");
if(vc.checkVowel('U')!= "true")System.out.println("error in code");
if(vc.checkVowel('J') == "true")System.out.println("error in code");
System.out.println("Testing Done");
}
}
6. replace the string vowel with specific characters
// replace the string vowel with specific characters
public class ReplaceVowelWIthChar5 {
public static void main(String [] args){
ReplaceVowelWIthChar5 cc = new ReplaceVowelWIthChar5();
cc.replaceVowel("hello world", '*');
// below for testing
cc.replaceVowel("oohelilo woruld", '-');
cc.replaceVowel("hEllO wOrld", '^');
cc.replaceVowel("OOhElIlO wOrUld", '~');
cc.replaceVowel("AAEEIfIOOUU", '*');
cc.replaceVowel("aapeeliinoovuu", '$');
}
public String replaceVowel(String msg, char ch){
ReplaceVowelWIthChar5 cc = new ReplaceVowelWIthChar5();
StringBuffer sb = new StringBuffer(msg);
for(int i=0; i< msg.length(); i++){
char oneCharFromList = msg.charAt(i);
if(cc.checkVowel(oneCharFromList)){
sb.setCharAt(i, ch);
}else
sb.setCharAt(i, oneCharFromList);
}
String xx = sb.toString();
System.out.println(xx);
return xx;
}
boolean checkVowel(char ch){
String vowelList = "AEIOU";
char ch1 = Character.toUpperCase(ch);
int x = vowelList.indexOf(ch1);
if(x!=-1){
return true;
}
else{
return false;
}
}
}
7. replace vowels with two different character present at even and odd place
// replace vowels with two different character if vowel present at even and odd place
public class ReplaceWithTwoChar6 {
public static void main(String [] args){
ReplaceWithTwoChar6 cc = new ReplaceWithTwoChar6();
cc.replaceVowel("hello world", '*','^');
// below for testing
cc.replaceVowel("oohelilo woruld", '-','@');
cc.replaceVowel("hEllO wOrld", '^','=');
cc.replaceVowel("OOhElIlO wOrUld", '~','%');
cc.replaceVowel("AAEEIfIOOUU", '*','#');
cc.replaceVowel("aapeeliinoovuu", '$',')');
}
public String replaceVowel(String msg, char ch1, char ch2){
ReplaceWithTwoChar6 cc = new ReplaceWithTwoChar6();
StringBuffer sb = new StringBuffer(msg);
for(int i=0; i< msg.length(); i++){
char oneCharFromList = msg.charAt(i);
int idx = i%2;
if(cc.checkVowel(oneCharFromList) && idx == 0 ){
sb.setCharAt(i, ch1);
}else if(cc.checkVowel(oneCharFromList) && idx!= 0 ){
sb.setCharAt(i, ch2);
}
else
sb.setCharAt(i, oneCharFromList);
}
String xx = sb.toString();
System.out.println(xx);
return xx;
}
boolean checkVowel(char ch){
String vowelList = "AEIOU";
char ch1 = Character.toUpperCase(ch);
int x = vowelList.indexOf(ch1);
if(x!=-1){
return true;
}
else{
return false;
}
}
}
8. replace given character with even odd position 3 parameters
// replace given chracter with even odd positon
public class ReplaceWithGivenChar7 {
public static void main(String [] args){
ReplaceWithGivenChar7 cc = new ReplaceWithGivenChar7();
cc.replaceVowel("hello world", 'o', '*', '^');
// below for testing
cc.replaceVowel("oohelilo woruld",'o', '-','@');
cc.replaceVowel("hEllO wOrld",'e', '^','=');
cc.replaceVowel("OOhElIlO wOrUld",'u', '~','%');
cc.replaceVowel("AAEEIfIOOUU",'o', '*','#');
cc.replaceVowel("aapeeliinoovuu",'i', '$',')');
}
public String replaceVowel(String msg, char ch1, char chOdd, char chEven){
StringBuffer sb = new StringBuffer(msg);
for(int i=0; i< msg.length(); i++){
char oneCharFromList = msg.charAt(i);
int idx = (i+1)%2;
if((oneCharFromList==ch1) && idx == 0 ){
sb.setCharAt(i, chOdd);
}else if((oneCharFromList==ch1) && idx!= 0 ){
sb.setCharAt(i, chEven);
}
else
sb.setCharAt(i, oneCharFromList);
}
String xx = sb.toString();
System.out.println(xx);
return xx;
}
}
9. simple dice , Random() mt, for 2 and 12
// simple dice , Random() mt, for 2 and 12
import java.util.Random;
public class SimpleSimulate8 {
public static void main(String [] args ){
SimpleSimulate8 cc = new SimpleSimulate8();
cc.simpleSimulate(2);
}
public void simpleSimulate(int rolls){
Random rand = new Random();
int twos =0;
int twelves =0;
for(int k=0;k<rolls;k++){
int d1 = rand.nextInt(6)+1;
int d2 = rand.nextInt(6)+1;
if(d1+d2 == 2){
twos +=1;
}
else if(d1+d2 == 12){
twelves += 1;
}
}
System.out.println("2's=\t"+ twos + "\t" + 100.0 * twos / rolls);
System.out.println("12's=\t"+ twelves + "\t" + 100.0 * twelves / rolls);
}
}
10. simple dice , Random() mt, for all combinations
// simple dice , Random() mt, for all combinations
import java.util.Random;
public class SimpleSimulateAll12Num9 {
public static void main(String [] args ){
SimpleSimulateAll12Num9 cc = new SimpleSimulateAll12Num9();
cc.simpleSimulate(200);
}
public void simpleSimulate(int rolls){
Random rand = new Random();
int twos =0;
int threes =0;
int fours =0;
int fives =0;
int sixs =0;
int sevens =0;
int eights =0;
int nines =0;
int tens =0;
int elevens =0;
int twelves =0;
for(int k=0;k<rolls;k++){
int d1 = rand.nextInt(6)+1;
int d2 = rand.nextInt(6)+1;
if(d1+d2 == 2){
twos +=1;
}
else if(d1+d2 == 3){
threes += 1;
}
else if(d1+d2 == 4){
fours += 1;
}
else if(d1+d2 == 5){
fives += 1;
}
else if(d1+d2 == 6){
sixs += 1;
}
else if(d1+d2 == 7){
sevens += 1;
}
else if(d1+d2 == 8){
eights += 1;
}
else if(d1+d2 == 9){
nines += 1;
}
else if(d1+d2 == 10){
tens += 1;
}
else if(d1+d2 == 11){
elevens += 1;
}
else{
twelves += 1;
}
}
System.out.println("2's=\t"+ twos + "\t" + 100.0 * twos / rolls);
System.out.println("3's=\t"+ threes + "\t" + 100.0 * twos / rolls);
System.out.println("4's=\t"+ fours + "\t" + 100.0 * twos / rolls);
System.out.println("5's=\t"+ fives + "\t" + 100.0 * twos / rolls);
System.out.println("6's=\t"+ sixs + "\t" + 100.0 * twos / rolls);
System.out.println("7's=\t"+ sevens + "\t" + 100.0 * twos / rolls);
System.out.println("8's=\t"+ eights + "\t" + 100.0 * twos / rolls);
System.out.println("9's=\t"+ nines + "\t" + 100.0 * twos / rolls);
System.out.println("10's=\t"+ tens + "\t" + 100.0 * twos / rolls);
System.out.println("11's=\t"+ elevens + "\t" + 100.0 * twos / rolls);
System.out.println("12's=\t"+ twelves + "\t" + 100.0 * twelves / rolls);
}
}
11. roll a dice and save the value in array make code shorter
// roll a dice and save the value in array make code shorter
import java.util.Random;
public class SSArrayAll12Num10 {
public static void main(String [] args){
Random rd = new Random();
int [] pos = new int[13];
int roll = 100; // how many time you want to roll a dice
int res = 0;
for(int k = 0; k<roll; k++){
int d1 = rd.nextInt(6)+1;
int d2 = rd.nextInt(6)+1;
int d3 = d1+d2;
System.out.println("result check : "+d1+ "+"+d2 + "=" + pos [d3]);
pos[d3]= pos[d3]+1;
}
for(int x = 2; x<13; x++){
// System.out.println(pos[x]);
float ss = 100*pos[x]/roll;
System.out.println(x+"'s=\t"+ pos[x] +"\t"+ ss);
res = pos[x]+res;
}
System.out.println("res : "+res);
}
}
// make array form 2 to 12
// loop 1 to 100 , roll a dice
// generate d1 and d2 values form 1 to 6
// so addition give index position 2 to 12
// if any position found, increment it to 1 and save it to that location
12. read words from a file and save it in the array
// read words from a file and save it in the array
// BufferedReader, readLine, split, FileReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SaveWordsFromFile11 {
public static void main(String [] args){
String [] wordlist = new String[20];
int index = 0; // Track the index for inserting words
try (BufferedReader rd = new BufferedReader(new FileReader("data/common.txt"))) {
String lnCont;
while ((lnCont = rd.readLine()) != null && index < 20) { // Stop if array is full
String[] words = lnCont.split("\\s+"); // Split line into words by whitespace
for (String word : words) {
if (index < 20) { // Only add if there is space in the array
wordlist[index++] = word; // Insert word and increment index
} else {
break; // Stop adding if the array is full
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Print out the words in the array
for (String word : wordlist) {
if (word != null) {
System.out.println(word);
}
}
}
}
// 1. make 20 lenght array
// 2. use buffer read to read file as text
// 3. extract first line using loop-1, till null
// 4. extract first word using loop-2
// 5. save above in array
// 6. again start point 3
// FileInputStream reads the raw bytes,
// BufferedReader with FileReader to read the file as text and process it word by word.
// readLine ( BufferedReader class ) Each call to readLine reads the next line until it
// reaches the end of the file (or another newline character). When it reaches the end // of the file, it returns null, which is why we often check for null in a loop to
// avoid reading past the end.
13. count number of words appear in the Shakespeare story form a list
// count number of words appear in the shakespera story form a list
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Shakhspear13 {
public static void main(String [] args){
Shakhspear13 shak1 = new Shakhspear13();
int x1 = shak1.findlenght("common.txt");
int x2 = shak1.findlenght("hamlet.txt");
System.out.println("total word in common list : "+x1);
System.out.println("total word in story list : "+x2);
Shakhspear13 shak = new Shakhspear13();
String [] st1 = new String[x1];
String [] st2 = new String[x2];
int [] res = new int[x1];
st1 = shak.findtotalwords("common.txt",x1); // find common word list and save it in st1 array;
st2 = shak.findtotalwords("hamlet.txt",x2); // find common word list and save it in st1 array;
for (int i=0;i<x1;i++) {
if (st1[i] != null) {
int count =0;
for(int j=0; j<x2; j++){
if(st1[i] != null && st2[j] != null && st1[i].equals(st2[j].toLowerCase())){
count = count+1;
res[i] = count;
}
}
}
}
for(int k=0; k<x1; k++){
if(st1[k] != null){
System.out.println(st1[k]+" = "+res[k]);
}
}
}
String [] findtotalwords(String fileName, int x3){
String [] wordlist = new String[x3];
int index = 0; // Track the index for inserting words
try (BufferedReader rd = new BufferedReader(new FileReader("data/"+fileName))) {
String lnCont;
while ((lnCont = rd.readLine()) != null && index < x3) { // Stop if array is full
String[] words = lnCont.split("\\s+"); // Split line into words by whitespace
for (String word : words) {
if (index < x3) { // Only add if there is space in the array
wordlist[index++] = word; // Insert word and increment index
} else {
break; // Stop adding if the array is full
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return wordlist;
}
// find the lengthor number of words , use for array initilization
int findlenght(String fileName){
int newlength = 0; // Track the index for inserting words
try (BufferedReader rd = new BufferedReader(new FileReader("data/"+fileName))) {
String lnCont;
while ((lnCont = rd.readLine()) != null ) { // Stop if array is full
String[] words = lnCont.split("\\s+"); // Split line into words by whitespace
for (String word : words) {
if (word!=null) { // Only add if there is space in the array
newlength = newlength+1;
} else {
break; // Stop adding if the array is full
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return newlength;
}
}
// find both index and save it in the array
// use nested for loop for comparing one list words to another list words
