convert uppercase letter to lowercase letter - java

Write a program called CaseConverter with a main method that converts a single uppercase letter to a lowercase letter. You have to declare a char variable to hold the lowercase letter.
public class CaseConverter {
public static void main (String [] args){
int offset = 'a' - 'A';
char temp = 'X'; // or any other uppercase alphabet
System.out.println("uppercase: " + temp);
// insert code here
System.out.println("lowercase: " + temp);
}
}

This can be used for case conersion
public char toLowercase(char c) {
int offset = 'a' - 'A';
if (c >= 'A' && c <= 'Z') {
return (char) (c + offset);
}
return c;
}
public char toUppercase(char c) {
int offset = 'a' - 'A';
if (c >= 'a' && c <= 'z') {
return (char) (c - offset);
}
return c;
}

Code of Uppercase alphabet 'A' is 67 and Code of Lowercase alphabet is 'a' is 97. So, the offset is 32. So, to convert any Uppercase alphabet to Lowercase alphabet you have to add 32 i.e. offset to it.
Edit:
public class CaseConverter{
public static void main(String args[]){
int offset = 'a' - 'A';
int temp = 'X'; // or any other uppercase alphabet
System.out.println("uppercase: " + (char)temp);
temp = temp + offset;
System.out.println("lowercase: " + (char)temp);
}
}
Edit: Since your temp data type is char, then this would work
public class CaseConverter{
public static void main(String args[]){
int offset = 'a' - 'A';
char temp = 'X'; // or any other uppercase alphabet
System.out.println("uppercase: " + temp);
temp = (char)((int)temp + offset);
System.out.println("lowercase: " + temp);
}
}

Your question can be easily answered if you look at the ASCII table. When you write a, the int variable will hold the ASCII value of the character a.
Look for example at the ASCII value of the letter P, it is 80. How do you get the ASCII value of p which is 112? I won't give you full solution but this should help you to begin*.
* 'a' - 'A' is 32

import java.io.*;
public CaseConverter{
public static void main(String args[]){
char temp = 'X'; // or any other uppercase alphabet
System.out.println("uppercase: " + temp);
System.out.println(temp.toUpperCase() );
}
}

offset:
lower case letters in ASCII code follows uppercase by 32 as I can remember so if you have an uppercase letter 'X' the you sub its int value by the difference between upper and lower case letters you get the lower.
char ch = 'x'; //x is lower case letter
int diff = (int)'a' - (int)'A'; //Difference between lower and upper
ch = (int)ch - diff; //now you get the lower case

use java Character class static method which convert upper case character to lowercase character :> Character.toLowerCase(c);

Related

Caesar Cipher Uppercase and Lowercase Wrap Around

I am having a problem regarding wrapping around the alphabet with my Caesar Cipher Program.
The program works fine with all lowercase letters. Wraps around perfectly and is able to apply positive and negative shifts. When i try to input an uppercase letter, the uppercase letter does not wrap around.
Here is my code:
public static StringBuilder encode(String str, int numShift)
{
numShift = numShift % 26;
//assign each character of the string to a position in the character array
char[] strChars = str.toCharArray();
for (int i = 0; i < strChars.length; i++)
{
//ignore and continue if the character is not within the alphabet
if((strChars[i] < 'a' || strChars[i] > 'z') && (strChars[i]<'A' || strChars[i] > 'Z'))
continue;
//apply the shift to each character
strChars[i] += numShift;
//wrap around if the shift is beyond Z
**if(strChars[i] > 'z')
{
strChars[i] -= 'z';
strChars[i] += ('a' - 1);
}**
}
StringBuilder encodedStr = new StringBuilder();
encodedStr.append(strChars);
return encodedStr;
}
public static void init(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the string that you would like to encode:");
String str = scan.nextLine();
System.out.println("Please enter the number of letters you would like to shift:");
int strShift = scan.nextInt();
scan.close();
StringBuilder result = encode(str, strShift);
System.out.println(result);
}
public static void main(String[] args)
{
init();
}
}
Hints would be much appreciated! Of course, I am not asking anyone to do my work for me but some help would be appreciated! Thank you! :)
Edit: here's the if statement that does the wrap around for lowercase letters only:
if(strChars[i] > 'z')
{
strChars[i] -= 'z';
strChars[i] += ('a' - 1);
}
Let's implement a wrap-around function for a single character. This will be used by the other method. When you separate your tasks and sub-tasks wisely, you will observe that your problem becomes easier to solve. Here I have based my solution on the fact that char variables are represented as numbers, we know the number of letters and we can use that number as a modulo class, to make sure that algebra is aiding us.
private static char wrapChar(char input, int amount) {
//assume for now that we have an upper-case letter
char start = 'A';
//if the assumption is mistaken...
if (('a' <= input) && (input <= 'z')) {
//then, if it is lower-case, then use lower-case
start = 'a';
} else if (!(('A' <= input) && (input <= 'Z'))) {
//target is not letter
return input;
}
//Calculate total offset compared to the first letter of the alphabet
//be it lower or upper
int offset = ((input - start) + amount) % 26;
//If offset happens to be negative, then shift a modulo period of 26
//To get the correct positive offset
if (offset < 0) {
offset += 26;
}
//Add the final offset to start and convert it to char
return ((char)(start + offset));
}
Now, instead of
//apply the shift to each character
strChars[i] += numShift;
//wrap around if the shift is beyond Z
**if(strChars[i] > 'z')
{
strChars[i] -= 'z';
strChars[i] += ('a' - 1);
}**
You need just:
strChars[i] = wrapChar(strChars[i], numShift);

How to create an array that contains 26 english letters but the order to be set by an input

I want to know how to create an array that contains 26 english letters but the order of them to be: e.g.
INPUT: problem
and the array would be:
'p','r','o','b','l','e','m','a','c','d','f','g','h','i','j','k','n','q','s','t','u','v','w','x','y','z'.
I tried to do it but i couldnt
My code is here
import javax.swing.JOptionPane;
public class TabelaEShkronjave {
public static void main(String[] args) {
char[][] square = new char[26][26];
/*char[] fjalaKyqe = {'p','r','o','b','l','e','m','a','c','d','f',
'g','h','i','j','k','n','q','s','t','u','v','w','x','y','z'};
*/
String word = JOptionPane.showInputDialog("Write a word: ");
char[] wordArray = word.toCharArray();
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
}
}
First off, you need to guard against bad input, such as non-letters, repeated letters, and uppercase vs. lowercase letters.
One way to build the desired result is to rely on behavior of LinkedHashSet, which will ignore duplicate inserts, so if we first add the letters of the input text, then all letters of alphabet, duplicates will be eliminated for us. The main problem is that the Set has to work with boxed Character objects, not plain char values.
private static char[] wordPrefixedAlphabet(String word) {
Set<Character> letters = new LinkedHashSet<>();
for (char c : word.toLowerCase().toCharArray())
if (c >= 'a' && c <= 'z')
letters.add(c);
for (char c = 'a'; c <= 'z'; c++)
letters.add(c);
char[] alphabet = new char[26];
int i = 0;
for (char c : letters)
alphabet[i++] = c;
return alphabet;
}
Another way is to keep track of which letters have already been added, using a boolean[26]:
private static char[] wordPrefixedAlphabet(String word) {
boolean[] used = new boolean[26];
char[] alphabet = new char[26];
int i = 0;
for (char c : word.toLowerCase().toCharArray())
if (c >= 'a' && c <= 'z' && ! used[c - 'a']) {
used[c - 'a'] = true;
alphabet[i++] = c;
}
for (char c = 'a'; c <= 'z'; c++)
if (! used[c - 'a'])
alphabet[i++] = c;
return alphabet;
}
Testing both with the input "That is NOT a problem!!" produces:
[t, h, a, i, s, n, o, p, r, b, l, e, m, c, d, f, g, j, k, q, u, v, w, x, y, z]
You could:
create an array, the size of the alphabet
copy into the array the characters of the word
selectively copy the characters of the alphabet not yet used
Something like this:
char[] wordArray = word.toCharArray();
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
char[] target = new char[alphabet.length];
System.arraycopy(wordArray, 0, target, 0, wordArray.length);
boolean[] used = new boolean[alphabet.length];
for (char c : wordArray.toCharArray()) {
used[c - 'a'] = true;
}
for (int k = 0, t = wordArray.length; t < target.length; ++k) {
char c = alphabet.chatAt(k);
int pos = c - 'a';
if (!used[pos]) {
target[t++] = c;
}
}
Psuedocode:
Get the length of the input string
Does the input string contain any duplicate characters?
Tip: Use stringName.charAt(i) and a for loop to test individual characters in string
If it doesn't contain any duplicate characters
For loop through string length (i)
For loop through alphabet length (j)
Find array position of stringName.charAt(i) in the alphabet array (j)
Swap this array character with current loop position (i).
(so 'a' and 'p' in problem swap)
Break
For loop through the alphabet array swapped out starting at string length (i)
if the (int) character is less than the next (int) character in loop
swap them and set (i) to string length to restart the for loop
Else
Print an error saying they don't have all unique characters in input
While this isn't the most efficient way to do it, it doesn't require any outside classes besides what you're already given, so it is useful if you are a beginner and need more practice in array manipulation and for loops.
After you read the input and got an array of chars from the input you can use the following logic to achieve desired result:
boolean contains(char[] arr, value) {
if (arr == null) {
return false;
}
for (char c : arr) {
if (c == value) {
return true;
}
}
return false;
}
...
char[] myOrderedAlphabet = new char[26];
int alphabetPosition = 0;
for (char c : wordArray) {
}
for (char c = 'a'; c <= 'z'; c++) {
if (!contains(myOrderedAlphabet, c) {
myOrderedAlphabet[alphabetPosition] = c;
alphabetPosition++;
}
}
Please note that this snippet does not check if character from wordArray is alphabetic. Hence if you will have characters which are not lowercase latin letters this code will cause an IndexOutOfRangeException. You might want to add some additional checks to the code above to prevent errors.
you could do it like this:
String word = JOptionPane.showInputDialog("Write a word: ");
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
char[] result = new char[alphabet.length];
int start = 0;
for (; start < word.length(); start++) {
result[start] = word.toCharArray()[start];
}
for (int i = 0; i < alphabet.length; i++) {
if(word.indexOf(alphabet[i]) == -1) {
result[start++] = alphabet[i];
}
}

Print 10 characters per line

hello i have some trouble doing my coding on this question;
Write a method that prints characters using the following header:
public static void printChars(char ch1, char ch2, int numberPerLine)
This method prints the characters between ch1 and ch2 with the specified numbers per line. Write test program that prints ten characters per line from ā€˜lā€™ and ā€˜Zā€™.
can somebody show me the coding sample to solve my problem? thanks
Here is some code that seems to wok on my end.
public static String alphabet = "abcdefghijklmnopqrstuvwxyz";
public static void printChars(char ch1, char ch2, int numberPerLine){
int currentNumber = numberPerLine;
int beginningIndex = alphabet.indexOf((ch1 + "").toLowerCase()) + 1;
int endingIndex = alphabet.indexOf((ch2 + "").toLowerCase());
for(int i = beginningIndex; i < endingIndex; i++){
System.out.print(alphabet.charAt(i));
if(currentNumber > 1){
currentNumber --;
}else{
System.out.println("");
currentNumber = numberPerLine;
}
}
}
public static void main(String[] args) {
printChars('c', 'z', 2);
}
Characters are encoded in ASCII. Each character has a unique decimal number representation. We can access these characters by their numbers, rather than the actual character.
For example, the character 'A' has an ASCII code of 65. We don't really need to know the integer codes to use their respective character representations though. We can just typecast the integers into chars.
We can also use characters in simple arithmetic. Since 'A' has ASCII code 65, then it makes sense for 65 + 1 = 66 to represent the character 'B'. Indeed it does.
public static void printChars(char ch1, char ch2, int numberPerLine) {
if(ch1 <= 'Z' && ch2 >= 'a')
return;
int count = 0; //count number of characters on a line.
char nextChar = ch1; //initialize our next character
while(nextChar <= ch2) { //test case
System.out.print(nextChar);
count++; //once we print a character, increment our count
if(count == numberPerLine) { //check if we reach our desired amount of characters
System.out.println();
count = 0; //once we print a new line, restart the count
}
nextChar = (char) (nextChar + 1); //get next character
}
}

Adding two character arrays and storing the result as characters in another char array in Java

I want to add two character arrays and store the result as characters in another character array.
The addition involves addition of two english letters from the two arrays as operands.
The addition will wrap around z back to a .
eg.
Input:Array1 and Array 2 and output is Array 3
Array 1 :abcdeyz
Array 2 :aaaaaaa
Array 3 :bcdefza
Below is a part of my code which is not working.
Kindly suggest any changes
int c = 0;
char array3[] = new char[count] ;
for(int a=0;a<array1.length;a++)
{
for(int b=0;b<array2.length;b++)
{
int temp = (array1[a] + array2[b]) % 26 ;
array3[c] = (char) temp ;
c++ ;
}
}
Hint - value of 'a' is not 0
The issue is in the line -
int temp = (array1[a] + array2[b]) % 26 ;
Here is the modified code (assuming all characters are lower case)-
int c = 0;
char array3[] = new char[count] ;
for(int a=0;a<array1.length;a++)
{
for(int b=0;b<array2.length;b++)
{
int temp = ( (array1[a]-'a') + (array2[b]-'a')) % 26 ;
array3[c] = (char) (temp+'a') ;
c++ ;
}
}
Using the modulo of 26 is a good way of handling a-z to 1-26 conversion. This way your program can be agnostic about the actual ASCII character numbers.
Some other concerns:
Case Insensitivity. I would recommend converting your letters to lowercase before processing them.
Handling of exceptional cases. What if your arrays are different lengths? Or what if they have a character that isn't a
letter?
The below code is one way to handle these things.
public static int letterToInt(char letter) {
char letterToConvert = Character.toLowerCase(letter);
int codeForA = (int)'a';
int numberOfLetter = ((int)letterToConvert) - codeForA + 1;
if(numberOfLetter < 1 || numberOfLetter > 26) {
throw new IllegalArgumentException(
"The character argument can only be a-z or A-Z, but was '" + letter + "'");
}
return numberOfLetter;
}
public static char intToLetter(int number) {
if(number < 1 || number > 26) {
throw new IllegalArgumentException(
"The number can only be 1-26, but was " + number);
}
int codeForA = (int)'a';
return (char)(codeForA + number - 1);
}
public static char addLetters(char letter1, char letter2) {
int numberFromAddedLetters =
letterToInt(letter1) + letterToInt(letter2);
int modulo = numberFromAddedLetters % 26;
return intToLetter(modulo == 0 ? 26 : modulo);
}
public static char[] addLetterArrays(char[] array1, char[] array2) {
char[] longerArray;
char[] shorterArray;
if(array1.length >= array2.length) {
longerArray = array1;
shorterArray = array2;
} else {
longerArray = array2;
shorterArray = array1;
}
char[] addedLetters = new char[longerArray.length];
for(int index = 0; index < longerArray.length; index++) {
if(index < shorterArray.length) {
addedLetters[index] = addLetters(longerArray[index], shorterArray[index]);
} else {
addedLetters[index] = longerArray[index];
}
}
return addedLetters;
}
// Test it out
public static void main(String[] args) {
char[] letters1 = "abcdeyz".toCharArray();
char[] letters2 = "aaaaaaa".toCharArray();
// Prints [b, c, d, e, f, z, a]
System.out.println(Arrays.toString(addLetterArrays(letters1, letters2)));
}
This is a fixed and working example on how to do this:
public static void main(String[] args) {
char[] array1 = new char[] {'a', 'b', 'c', 'd', 'e', 'y', 'z'};
char[] array2 = new char[] {'a', 'a', 'a', 'a', 'a', 'a', 'a'};
char[] array3 = new char[array1.length];
for (int i = 0; i < array1.length; i++) {
array3[i] = toChar((toInt(array1[i]) + toInt(array2[i]) + 1) % 26);
}
System.out.println(Arrays.toString(array3));
}
private static int toInt(char chr) {
return chr - 'a';
}
private static char toChar(int value) {
return (char)(value + 'a');
}
There are some thinks to notice here (except the - 'a' part, the other answers mentioned that already):
you only need one loop for this task. If you use 2 nested loops, then you'll add each letter of array1 with every letter of array2. And you'll a larger array3. And since the result doesn't match the desired result ... :)
the + 1 in toInt(array2[i]) + 1 is necessary, because char - 'a' is "zero-based". Therefore 'a' + 'b' would result in 'b' and not 'c', because you'll calculate 0 + 1 (which will be 'b' if you "convert" it back to char by adding 'a') (I hope this is understandable expressed :D)
it is necessary that array2 has at least the same length as 'array1'. It is almost like padding in cryptography. (I've omitted the padding part to keep this code short)
Write this:
int temp = (((array1[a] - 'a') + (array2[b] - 'a')) % 26) + 'a';
what this does is convert both characters into their respective place in the alphabet, perform addition modulo the number of characters in the alphabet for the wraparound effect, and convert back to the correct ascii value.
Note that your code was having trouble because you were acting as though the alphabet's ascii values were their respective places in the alphabet itself, which is incorrect.

Convert a letter to the corresponding letter on the opposite counting direction in the alphabet

I am self-studying Java and I am very at the beginning learning the basics. With below code I am trying to convert a letter to the corresponding letter on the opposite counting direction in the alphabet(i.e A to Z or Z to A etc.). It works for a single letter but not for a series of letters. How can I make it work with more than one letter? If you can use the simplest way it would be good as I am quite new in Java. I don't(know how to) export any built in classes etc.
Thank you.
class Turner{
int find(int fin, int mi,int ma,char ch[]){
int mid = (ma+mi)/2;
int x;
if(ch[mid]==fin)
return mid;
else if(fin<ch[mid])
return(find(fin, mi,mid-1,ch));
else
return x = find(fin,(mid+1),ma,ch);
}
}
class Turn {
public static void main(String args[]) throws java.io.IOException
{
Turner try1 = new Turner();
char arra[] = new char[26];
char arrb[] = new char[26];
int min = 0;
int max = arra.length;
char a = 'A';
char b = 'Z';
int i;
char letter;
for(i=0;i<26;i++)
{
arra[i]=a;
a++;
arrb[i]=b;
b--;
}
System.out.println("Enter a letter: ");
letter = (char)System.in.read();
System.out.print(arrb[try1.find(letter,min,max,arra)]);
}
}
Have you considered just doing some math?
letter = Character.toUpperCase((char)System.in.read());
System.out.print((char)('Z' - (letter - 'A'));
And it works for only one letter because you are not repeating the conversion procedure. The program reads one char, prints its opposite and then terminates.
All you have to do is to put the read and print code inside some sort of loop, so every time it runs it will promptly wait for the next letter.
while (true) {
letter = Character.toUpperCase((char)System.in.read());
if ((letter > 'Z') || (letter < 'A'))
break; // user inputted an invalid symbol, terminating the program
System.out.print((char)('Z' - (letter - 'A')));
}
If your function (they are called methods in java) works, good. Just put it in a while loop or otherwise call it when you need it.
boolean done = false;
while(!done){
System.out.println("Enter a letter (space to quit): ");
letter = (char)System.in.read();
if(letter == ' ') done = true;
else System.out.print(arrb[try1.find(letter,min,max,arra)]);
}
And Havenard is right, this can be written considerably more simply, with arithmetic on chars. For instance ch -'a' == 1 evaluates to true when ch is 'b'.
One other note: find and Turner aren't very descriptive names for what these things do. Before long it could get messy without simple and to the point naming.
A character has an equivalent numerical value. For "basic characters", this mapping is called ASCII table: http://www.asciitable.com/
Now, in java, you can convert a char into an int by casting. Example: int nValue=(int) 'a'.
Since there is a numerical value associated to 'a' and another one associated with 'z', you could use some simple math to solve your problem.
See:
int aNumericalValue = (int) 'a';
int zNumericalValue = (int) 'z';
char characterToConvert = ...;
int characterToConvertAsNumericalValue = (int) characterToConvert;
int resultCharacterAsNumericalValue = zNumericalValue - (characterToConvertAsNumericalValue - aNumericalValue);
char resultCharacter = (char) resultCharacterAsNumericalValue;
Or, you could write all of this as a single line of code:
char resultCharacter = (char) ((int) 'z' - ((int) characterToConvert - (int) 'a'));
And finally, if you are willing to hardcode some ASCII values:
char resultCharacter = (char) (122 - ((int) characterToConvert - 97));
Note that this is for lowercase letters. For caps, use 'A' (ascii 65), 'Z' (ascii 90).

Categories

Resources