❌

Reading view

There are new articles available, click to refresh the page.

Playing with Char Array

    // 1. REMOVING UNWANTED SPACE
    // 2. CAPITALIZE EACH WORD
package taskPkg;

import java.util.Scanner;

public class PlayingWithCharAr {

	public static void main(String[] args) {
		// 1. REMOVING UNWANTED SPACE
		// 2. CAPITALIZE EACH WORD
		Scanner scn = new Scanner(System.in);
		System.out.println("Enter a sentence...");
		String sentence = scn.nextLine();
		scn.close();
		char[] sen = sentence.toCharArray();
		PlayingWithCharAr obj = new PlayingWithCharAr();
		obj.removeSpace(sen);
		obj.wordStartWithCaps(sen);
	}

	private void removeSpace(char[] words) {
		int k = 0, n = words.length;
		System.out.print("Removed unwanted spaces :");
		while (k < n && words[k] == ' ')
			k++;
		for (; k < n - 1; k++) {
			if (!(words[k] == ' ' && words[k + 1] == ' '))
				System.out.print(words[k]);
		}
		if (words[n - 1] != ' ')
			System.out.print(words[n - 1]);
		System.out.println();
	}

	private void wordStartWithCaps(char[] words) {
		int i = 0, n = words.length;
		System.out.print("Capitalize Each Word :");
		if (words[i] != ' ')
			System.out.print((char) (words[i] - 32));
		for (i = 1; i < n; i++) {
			if (words[i - 1] == ' ' && words[i] != ' ' && (words[i] >= 'a' && words[i] <= 'z'))
				System.out.print((char) (words[i] - 32));
			else
				System.out.print(words[i]);
		}
	}

}

OUTPUT:

Password Validator

import java.util.Scanner;

public class PasswordValidator {

	public static void main(String[] args) {
		// PASSWORD MUST CONTAIN MIN 8 CHARS, MAX 12 CHARS, ATLEAST 1 UPPERCASE, 1 LOWERCASE, 1 DIGIT, 1 SPL CHAR 
		Scanner scn = new Scanner(System.in);
		int maxLen = 12, minLen=8;
		System.out.println("Enter a password to validate");
		String pwd = scn.next();
		scn.close();
		int n = pwd.length();
		if (n<minLen || n>maxLen) {
			System.out.println("Password length must be between 8 to 12 characters");
			return;
		}
		char[] pw = pwd.toCharArray();
		int cntLower=0, cntUpper=0, cntDigit=0, cntSpl=0;
		for (int i=0; i<n; i++) {
			char ch = pw[i];
			if (ch>='A' && ch<='Z') cntUpper++;
			else if (ch>='a' && ch<='z') cntLower++;
			else if (ch>='1' && ch<='9') cntDigit++;
			else if (ch=='!' || ch=='Β£' || ch=='$' || ch=='%' || ch=='^' || ch=='&' || ch=='*' || ch=='-' || ch=='_' || ch=='+' || ch=='=' || ch==':' || ch==';' || ch=='@'|| ch=='#'|| ch=='~'|| ch=='>'|| ch=='<'|| ch=='?'|| ch=='.') cntSpl++; 
		}
		if (cntLower>0 && cntUpper>0 && cntDigit>0  && cntSpl>0) System.out.println("Password is valid...");
		else {
			System.out.println("Password is NOT VALID");
			System.out.println("PASSWORD MUST CONTAIN ATLEAST 1 UPPERCASE, 1 LOWERCASE, 1 DIGIT AND 1 SPL CHAR FROM ! Β£ $ % ^ & * - _ + = : ; @ ~ # ?");
		}
	}

}

❌