This is probably a simple fix but I can't seem to solve it.
I am trying to add an integer to the ascii value of characters during a for loop.
It is giving me the error that the program expects a variable rather than a value. How can I do what I am trying to do here?
Here is the code:
public boolean toggleEncryption(){
if(encrypted == false){
for(int i = 0; i < sentence.length(); i++){
if(sentence.charAt(i) >= 65 && sentence.charAt(i) <= 90){
int x = (int)sentence.charAt(i);
x += key;
while(x > 90){
x = x - 26;
}
sentence.charAt(i) += (char)x;
}
}
}
return encrypted;
}
the line sentence.charAt(i) += (char)x; is not working for me
Simple:
sentence.charAt(i) += (char)x;
You wrongly assume that charAt() gives you a "left hand side" thingy. In other words: something that you can assign a value to; like a variable.
But this is not possible: charAt() returns an char value; that represents the char within the string at that index.
It does not give you something that allows you to manipulate the string itself! Strings are immutable; you can't use charAt() to modify its content!
In other words; you can do this:
char c = 'a';
c += 'b';
but you can't use charAt() to achieve the same!
Thus, in order to make your code work, you have to build a new string, like:
StringBuilder builder = new StringBuilder(sentence.length());
for(int i = 0; i < sentence.length(); i++) {
if(sentence.charAt(i) >= 65 && sentence.charAt(i) <= 90){
int x = (int)sentence.charAt(i);
x += key;
while(x > 90){
x = x - 26;
}
builder.append(sentence.charAt(i) + (char)x));
} else {
builder.append(sentence.charAt(i));
}
}
(disclaimer: I just wrote down the above code; there might be typos or little bugs in there; it is meant to be "pseudo code" to get you going!)
Beyond that: I find the name of that method; and how it deals with that boolean field ... a bit confusing. You see, if encryption is true ... the method does nothing?! Then it doesn't "toggle" anything. Thus that name is really misleading resp. not matching what your code is doing!
Here charAt(i) returns a char:
sentence.charAt(i) += (char)x;
1) You cannot assign a character to a value but you can do it to a variable.
2) Even if you used a variable such as
char tempChar = sentence.charAt(i);
You cannot do then :
tempChar += (char)x;
As you cannot increment (+=) a character with another character.
Related
String input = stack.pop();
if ((index = input.indexOf('*')) != -1) {
for (char c = '0'; c <= '1'; c++) {
input = input.substring(0, index) + c +
input.substring(index + 1);
stack.push(input);
}
}
I'm struggling to understand what's happening in the for loop. Can someone clarify how it iterates? I'm not used to having something other than the length of the array as the second parameter.
When you write for loop like this c have value = 48 accord to ascii table when you increment c it go up to 49 which is equal to 1 also from ascii. So now if you know that you can change your code to this
for (int c = 48; c <= 49; c++)
{
//your code
}
And it is the same. But if you concatenate string like you did value 48 is convert to 0,so * is gonna be replace with 0, in next iteration will be replace with 1.
Hello friends I am using online judge for practice
I try this question for a long time to try pass all tests but it is failing 1 test
Here is the code
public static String caesarCypherEncryptor(String str, int key) {
char[] newLetters = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
int newLetterCode = str.charAt(i) + key;
if (newLetterCode <= 122) {
newLetters[i] = (char)(newLetterCode);
} else {
newLetters[i] = (char)(96 + newLetterCode % 122);
}
}
return new String(newLetters);
}
Please point me in direction of want is reason for fail test
Think about what will happen when the passed in key is large enough such that newLetterCode % 122 is greater than 26.
newLetters[i] will not be a lowercase ASCII letter, right? Because the ASCII code for z is 122.
An easy fix for this is to simply change the line:
int newLetterCode = str.charAt(i) + key;
to
int newLetterCode = str.charAt(i) + key % 26;
This will prevent newLetterCode from ever being greater than 147. Which means newLetters[i] will always be a letter within a-z which your code currently is not enforcing.
I'm really loosing my hair over this one. Im making a (simple) encryption program.
Its supposed to take the char make it to an int, add 13 and convert back to a char. Then its supposed to do the same in reverse order. But my only outprint is two blank lines? I know the problem is when I convert back to letters for when I print x everything works. The part I've commented out was something I tried, and while I got an output endtwo was newer like the original text. Also I have to do this in modul 26.
String str = ("helloworld");
String end ="";
String endtwo ="";
for(int i = 0; i < str.length(); i++){
int x = str.charAt(i);
x = ((char)((x+13)%26));
char u =(char)x;
end += u;
//end += ((char)(str.charAt(i)+13));
}
for(int i = 0; i < str.length(); i++){
int x = str.charAt(i);
x = ((char)((x-13)%26));
char u =(char)x;
endtwo += u;
//endtwo += ((char)(str.charAt(i)-13));
}
In Java a char is an integer. Notice that the line
int x = str.charAt(i);
returns an integer which represents the character at the ith location in the String. So what is the value of the integer? You can look up the ASCII table for the letters of the alphabet. You will see that lower case h is 104 in decimal. So you then add 13 to this value so
104 + 13 = 117
You then proceed to mod by 26 which reduces the value to a range 0 to 25.
117 % 26 = 13
Decimal 13 in the ASCII table represents the carriage return character.
Similarly, going the other way you are starting with the 13 and subtracting 13 giving 0 then 0 mod 26 is 0 so 0 is the null character in the ASCII table.
Therefore, rethink your strategy for the encryption algorithm. For example, to get a simple cyclic cipher you can subtract the lower case character 'a' from the character to be encoded.
x = x - 'a';
x = x + 13;
x = x % 26;
x = x + 'a';
This guarantees that you end up with a letter of the alphabet. But only lower case though. How would you modify this to cater for upper case as well?
Also think carefully about the decipher step at the end. Subtracting 13 does not necessarily give you the answer you expect. Hint: Try running the cipher text through the exact same process as the encryption and see what happens.
A very simple approach to implement the ROT13 encryption algorithm is to check in wich range of ASCCI codes is each character, then add 13 or sub 13 depending on the range:
String str = "helloworld";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'A' && c < 'N' || c >= 'a' && c < 'n') {
c += 13;
} else if (c >= 'N' && c <= 'Z' || c >= 'n' && c <= 'z') {
c -= 13;
}
}
I am writing an Atoi function in Java. It runs fine for +ve integers. But what I want is when I enter a negative integer it should give me an error. So I tried including continue statement in my class Atoi. The class implemented is:
class Atoi {
int atoi(String tmp) {
int result = 0;
for (int i = 0; i < tmp.length(); i++) {
char digit = (char)(tmp.charAt(i) - '0');
if(digit == '-')
continue;
}
else {
result += (digit * Math.pow(10, (tmp.length() - i - 1)));
}
return result;
}
}
But unfortunately it gives me the negative equivalent of the character i.e for -12 it gives me 655312! Help.
EDIT: Suppose I need to check for floating point numbers what should I do? If I enter 12.1 or 123.2 it should return 12.1 and 123.2 repectively!!
Instead of continue you should give an error (throw an exception, return -1 or whatever you mean with "give an eror").
If you want to ignore the - you can change the else clause to:
result = digit + result * 10;
Quick fix for the obvious problem: the order of the logic was wrong...
Instead of
char digit = (char)(tmp.charAt(i) - '0');
if(digit=='-')
continue;
try
char origChar=tmp.charAt(i);
if(origChar=='-')
continue;
char digit = (char)(origChar - '0');
But there are two more problems:
it does not negate the value, in case of a '-' character is present!
what if this is the input string: -1-2-3-4-5? The result will be interesting! EDIT: try this input also: 'répa'... Even more interesting result!
Don't forget to test with incorrect inputs too, and as #Klaus suggested, don't hesitate to throw an exception, (preferably IllegalArgumentException) with a correct error message, if an incorrect input is given to the function...
If this is not being done as a programming exercise, there is a simpler solution:
static int atoi(String tmp)
{
int result = Integer.parseInt(tmp);
if(result >= 0) {
return result;
} else {
throw new IllegalArgumentException("Negative string "+"\"" + tmp + "\"");
}
}
Substitute the appropriate exception or other action in the negative result case. If you want to just ignore '-', as in the posted code, replace the if-then-else with:
return Math.abs(result);
This code also throws an exception for strings like "abc".
More generally, if a library method does not do exactly what you want, it is often easy to use it in a method that modifies its behavior, rather than re-writing it.
You can write code like this, of course, but you need to check that tmp is a valid number.
int atoi(String tmp) {
int result = 0;
int factor = tmp.charAt(0) == "-" ? -1 : 1;
for (int i = 0; i < tmp.length(); i++) {
if (tmp.chatAt(i) < '0' || tmp.chatAt(i) > '9')
continue;
char digit = (char)(tmp.charAt(i) - '0');
result += (digit * Math.pow(10, (tmp.length() - i - 1)));
}
return result * factor;
}
if(digit=='-')
With
(char)(tmp.charAt(i)
You're code is assuming there are no -'s
(char)(tmp.charAt(i) - '0');
Is an optimization that's blindly clamping the 'digit' variable to a number.
You need to step through what your code is actually doing, search for an ASCII chart and work through what the subtractions of '0' does ('0' == 48), so '1' (49) - '0' (48) = 1 etc...
If you don't want to convert negative numbers then simply return 0 whenever you encounter - sign instead of looping further. Put this code before the if-else block.
if(tmp.charAt(i)=='-')
return 0;
Why when comparing a char against another it must be taken also from a string? For example;
This does not work
while(i < t.length() && zeroCount < 5) {
if(t.charAt(i) == 0){
zeroCount++;
}
i++;
}
Nor does this
char zero = 0;
while(i < t.length() && zeroCount < 5) {
if(t.charAt(i) == zero){
zeroCount++;
}
i++;
}
The only way I managed to get it working is like this...
String zeros = "0000000000";
while(i < t.length() && zeroCount < 5) {
if(t.charAt(i) == zeros.charAt(i)){
zeroCount++;
}
i++;
}
Can anyone explain if am doing something wrong, or if it is just not acceptable to do it like the top 2 examples. If so, why?
You're confusing
char zero = 0;
with
char zero = '0';
The former is the null-character (ASCII value of zero), whereas the latter is the character representing the digit zero.
This confusion is a rather unfortunate hang-over from C, with char variables being treated as numbers as well as characters.
You are looking for the character '0'? Then compare to '0', not 0.
You're comparing against Unicode value 0 (aka U+0000, the "null" character) - which is not the same as the Unicode character representing the digit 0.
Use '0' instead of 0:
while(i < t.length() && zeroCount < 5) {
if(t.charAt(i) == '0'){
zeroCount++;
}
i++;
}
Use '0' instead of 0.
The simple answer is that the value 0 is not the same as the character '0' which has an ASCII code of 48 (IIRC).
You should compare it with the char value charAt(i) == '0' or subtract the char before comparison charAt(i) - '0' == 0
These other answers have it right, but there’s one very important thing you should know. You should never use chatAt! You should only use codePointAt.
Similarly, you mustn’t blindly use i++ to bump through a string. You need to see whether s.codePointAt(i) > Character.MAX_VALUE to know whether to give an extra i++ kicker.
For example, to print out all the codepoints in a String s in standard "U+" notation:
private static void say_U_contents(String s) {
System.out.print("U+");
for (int i = 0; i < s.length(); i++) {
System.out.printf("%X", s.codePointAt(i));
if (s.codePointAt(i) > Character.MAX_VALUE) { i++; } // UG!
if (i+1 < s.length()) { System.out.printf("."); }
}
}
That way you can output like U+61.DF, U+3C3, and U+1F4A9.1F4A9 for the corresponding strings. That last one looks like "\uD83D\uDCA9\uD83D\uDCA9", which is simply insane.