What I have so far
public String toUpperCase(String str)
{
int strLength = str.length();
String word = "";
while (strLength > 0)
{
char newStr = str.charAt(strLength);
Character.toUpperCase(newStr);
Character.toString(newStr);
word += newStr;
strLength--;
}
return word;
}
I'm completely lost and my code is probably illogical. Some help would be appreciated
To change string into uppercase without using toUpperCase(), then check below code.
if(ch>96 && ch<123)
{
ch=ch-32;
System.out.print( (char) ch);
}
check char small letter or not , if small then subtract it from 32
The Character.toUpperCase() function returns a character. You have to hold that value in a char literal.
Plus, you should begin the loop at strLength - 1 otherwise it'll throw a StringIndexOutOfBounds error. And, you should iterate till the index 0. At present, you iterate from strLength till 1.
Lastly, since you are iterating in the opposite direction, you should take care of the way you append the characters.
public String toUpperCase(String str)
{
int strLength = str.length();
String word = "";
while (--strLength >= 0)
{
char newChar = str.charAt(strLength);
newChar = Character.toUpperCase(newChar);
word = newChar + word; //appending in reverse order
}
return word;
}
NOTE
Since you are asked to write the function considering that the function doesn't exist, it would be less ironical to NOT use the Character.toUpperCase() method. Even I have used it. In that case, you can take a look at #Sam's suggestion. The above code will then have this modification:
char newChar = str.charAt(strLength);
if((int)newChar > 96 && (int)newChar < 123)
newChar = newChar - 32;
//the if statement is the replacement of the Character.toUpperCase()
//function call
You should take a look at the ASCII table.
char are integer, 'A' to 'Z' is 65 to 90 and 'a' to 'z' is 97 to 122.
So if you have a char between 'a' and 'z' you want to substract the difference betwin 'A' and 'a' to your char.
'a' - ('a' - 'A') = 'A'
'c' - ('a' - 'A') = 'C'
So you need to iterate on your string and do your math on each character.
public static char myUpper(char c){
if (c >= 'a' || c <= 'z'){
c = (char) (c - ('a' - 'A'));
}
return c;
}
Personally this is what I would do.
String newsentence =""; String question="HeLlo";
String caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lowerCase = "abcdefghijklmnopqrstuvwxyz";
for(int i=0;i<caps.length();i++) {
for(int j=0;j<caps.length();j++) {
if(question.equals(lowerCase.subString(j,j+1)){ newsentence+= (caps.subString(i,i+1); }
}} System.out.print(newsentence);
This is what I would do.
Related
I need to build a Caesar cipher that only encrypts letters, but no special characters. My concept was, to compare the input char[] with two alphabet char[]. If there is no match in a char, the char should be added to the String without being changed. The problem is that the not-changed char will be added to the String until the the for-loop ends. How do I fix this?
public static String encrypt(String text, int number) {
String str = "";
char[] chars = text.toCharArray();
char[] al = "abcdefghijklmnopqrstuvwxyz".toCharArray();
char[] ab = "abcdefghijklmnopqrstuvwxyz".toUpperCase().toCharArray();
for (char c : chars) {
boolean match = false;
for (int i = 1; i < chars.length - 1; i++) {
for (int k = 0; (k < al.length || k < ab.length) && !match; k++) {
match = (c == al[k] || c == ab[k]);
if (match) {
c += number;
str += c;
}
}
if (!match) {
str += c;
}
}
}
return str;
}
I already tried to put the case for not changing the string within the other for-loop, but it will be added until the for-loop has reached it's end.
I would tackle the problem by iterating through the String and considering the possible cases for each letter
Uppercase Letter
Lowercase Letter
Special Character
public static String encrypt(String text, int number) {
//String to hold our return value
String toReturn = "";
//Iterate across the string at each character
for (char c : text.toCharArray()){
if (Character.isUpperCase(c)){
/* If uppercase, add number to the character
If the character plus number is more than 90,
subtract 25 [uppercase letters have ASCII 65 to 90] */
toReturn += c + number > 90 ? (char)(c + number - 25) : (char)(c + number);
} else if (Character.isLowerCase(c)){
/* If lowercase, add number to the character
If the character plus number is more than 122,
subtract 25 [uppercase letters have ASCII 97 to 122] */
toReturn += c + number > 122 ? (char)(c + number - 25) : (char)(c + number);
} else {
// For other characters, just add it onto the return string
toReturn += c;
}
}
return toReturn;
}
Explanation of Code
You might be wondering what the following code does
toReturn += c + number > 90 ? (char)(c + number - 25) : (char)(c + number)
The structure is
toReturn += CONDITION ? A : B
It basically reads as
IF CONDITION IS TRUE, toReturn += A, ELSE toReturn += B
The CONDITION is simply c + number > 90 since we want to make sure that we are sticking with uppercase letters only
When this is true (A), we subtract 25 from c + number, otherwise (B) we just keep it as c + number (B)
We then cast this value into a char since it is initially an int
This is what I have:
class encoded
{
public static void main(String[] args)
{
String s1 = "hello";
char[] ch = s1.toCharArray();
for(int i=0;i<ch.length;i++)
{
char c = (char) (((i - 'a' + 1) % 26) + 'a');
System.out.print(c);
}
}
}
So far I've converted the string to an array, and I've worked out how to shift, but now I'm stuck.
What I want is for the code to start at ch[0], read the character, shift it one to the right (h to i) and then do the same for each character in the array until it reaches the end.
Right now, my code outputs opqrs. I want it to output ifmmp. If I replace the int i = 0 in the for loop with int i = ch[0], it does start at i, but then it just inputs ijklmno...
I want it to read h, output as i, read e, output as f, and so on until it reaches the end of the array.
You are using the loop index i instead of the ith character in your loop, which means the output of your code does not depend the input String (well, except for the length of the output, which is the same as the length of the input).
Change
char c = (char) (((i - 'a' + 1) % 26) + 'a');
to
char c = (char) (((ch[i] - 'a' + 1) % 26) + 'a');
Replace i - 'a' + 1 with ch[i] - 'a' + 1
class encoded {
public static void main(String[] args)
{
String s1 = "hello";
char[] ch = s1.toCharArray();
for(int i=0;i<ch.length;i++)
{
char c = (char) (((ch[i] - 'a' + 1) % 26) + 'a');
System.out.print(c);
}
}
}
I am quite at a loss here, i am to create a java programm which takes a String and decodes/encodes the string with n.(It adds n to the chars of the string like n=3 a=c) I buitl the "shell" which takes the user to the action he would like the programm to perform, then i dont get how to encode/decode the string with the key, it has to consider upper/lowercase and ignore special symbols like )/!/&"$;:.,, there has to be something with "for" and a chararray which i never worked with before and do not understand...
All help appreciated!
heres the code so far! https://gist.github.com/fabiomim/070d1daeee4b604db720adf7c7dff240
(ignore the little rant in fachklasse)
Some hints:
you can get the characters by using the charAt(int) or toCharArray() methods of String:
String string = ...
char ch = string.charAt(i);
// or
char[] characters = string.toCharArray();
char ch = characters[i];
A char is a Integral Type, that is, an integer type and you can do arithmetic with it, like comparison, addition, subtraction:
char ch = ...
if (ch >= 'a' && ch <= 'z') {
// do something it the char is between 'a' and 'z'
ch += 3; // 'a' will become 'd', 'z' will be '}'!!!!
if (ch > 'z') {
// handle overflow like subtracting 'z'+1 - 'a'
}
}
To create a String from the char array, you can use:
String result = new String(characters);
Note that a char is not an int, you need a cast to assign it to a char variable:
ch = ch + 3; // ERROR since "ch + 3" is an int
ch = ch + 'a'; // ERROR the result of + is still an int!
ch = (char) (ch + 3);
ch = (char) (ch + 'a');
So I'm learning about functions and methods, and trying to create a function that would allow me to replace a Letter with a Number, thus "a" would be 0, "b" would be 1, so on and so forth. I don't know ascii at all, and have only run into creating a very long if, else statement, but I don't even know if I'm on the right track. I'm trying to find a way to create a function without having to make a long conditional statement and use less line of code.
This is the new code I have written with suggestions:
public class CaesarCipher {
/*
* create function that converts a letter to a number
* ex. a -> 0, b -> 1, etc...
*/
static char letterToNumber (char firstLetter){
if (firstLetter < 'a' || firstLetter > 'z') {
}
return firstLetter;
}
static int numberToLetter (int firstNumer){
if (firstNumber < '0' || firstNumber '25'){
}
return firstNumber;
}
public static void main(String[] args) {
char a = 0;
// TODO Auto-generated method stub
System.out.println (letterToNumber (a)); //suppose to compile to convert a -> the number 0
System.out.println(numberToLetter (1)); //compile to convert 1 -> the letter b
}
}
The simplest approach is just to subtract the literal 'a'... which will implicitly convert both your input letter and the 'a' to int:
public int convert(char letter) {
if (letter < 'a' || letter > 'z') {
throw new IllegalArgumentException("Only lower-case ASCII letters are valid");
}
return letter - 'a';
}
The nice thing about this solution is that it's reasonably "obviously correct" (with the assumption that the letters 'a' to 'z' are consecutive in UTF-16). You don't need to include any magic integer values.
char letter = 'a';
int letterAscii = (int)c;
int asciiOffsetOfA = 97;
int positionInAlphabet=letterAscii-asciiOffsetOfA;
Use this with combination of String.toCharArray() and String.toLowerCase() on your input String.
The ASCII value of 0 is 48, a is 97 and A is 65. So to convert small letter to 0 you decrease 49 and capital letter 17. Same goes for B/b and 1, C/c and 2, etc.
int smallChar = 'a' - 49; // equal 0
int capitalChar = 'A' - 17; // equal 0
I'm trying to implement a basic Caesar Shift Cipher for Java to shift all the letters by 13. Here's my code so far.
public static String cipher(String sentence){
String s = "";
for(int i = 0; i < sentence.length(); i++){
char c = (char)(sentence.charAt(i) + 13);
if (c > 'z')
s += (char)(sentence.charAt(i) - 13);
else
s += (char)(sentence.charAt(i) + 13);
}
return s;
}
However, the program also changes the values of numbers and special characters and I don't want that.
String sentence = "abc123";
returns "nop>?#"
Is there a simple way to avoid the special characters and only focus on letters?
Edit: I should mention I want to keep all the other bits. So "abc123" would return "nop123".
In the following example I encrypt just the letters (more precisely A-Z and a-z) and added the possibility to use any offset:
public static String cipher(String sentence, int offset) {
String s = "";
for(int i = 0; i < sentence.length(); i++) {
char c = (char)(sentence.charAt(i));
if (c >= 'A' && c <= 'Z') {
s += (char)((c - 'A' + offset) % 26 + 'A');
} else if (c >= 'a' && c <= 'z') {
s += (char)((c - 'a' + offset) % 26 + 'a');
} else {
s += c;
}
}
return s;
}
Here some examples:
cipher("abcABCxyzXYZ123", 1) // output: "bcdBCDyzaYZA123"
cipher("abcABCxyzXYZ123", 2) // output: "cdeCDEzabZAB123"
cipher("abcABCxyzXYZ123", 13) // output: "nopNOPklmKLM123"
Note: Due to your code, I assumed that you just want to handle/encrypt the "ordinary" 26 letters. Which means letters like e.g. the german 'ü' (Character.isLetter('ü') will return true) remain unencrypted.
Problem is that you add 13 as a fixed number, and that will for some letters (in second half of alphabet mostly and digits) produce characters that aren't letters.
You could solve this by using array of letters and shifting through those characters. (similar for digits) So something like this
List<Character> chars = ... // list all characters, separate lists for upper/lower case
char c = chars.get((chars.indexOf(sentence.charAt(i)) + 13)%chars.size());