Would any one be able to explain what this code does?
if ((x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z')){}
where x is an int.
However I am not entirely sure how it works, would any one be able to provide me with an explanation? If anyone needs more details please comment below rather than down voting my question.
You can initialize an int with a char type because, the code of char can be represented with an int so for example :
char x = 'A';
int i = x;
System.out.println((int)x);//this will print 65
System.out.println(i);//this will print 65
The code of char A is 65 so for that you can compare a char with int in your case : if ((x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z')){} you can also take a look here Java - char, int conversions
This code compare x to the ASCII code of A, Z... You can check there values in the ASCII table.
A verbal expression of your if-statement could be:
"If x value is the ASCII code of a letter (uppercase or not)."
Related
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.
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 have a car Object which is supposed to have a characteristic. The characteristic is supposed to have the requirements: starts with two capital letter followed by a number from 1-9 followed by 4 numbers from 0-9.
public void writeCharacteristic(){
System.out.println("write down the characteristic for the car.");
String characteristic = kb.nextLine();
progress = false;
if (characteristic.length() != 7){
System.out.println("The string is not 7 letter/numbers long");
progress = false;
}
for(int i = 0; i < 2; ++i){
if (characteristic.charAt(i) < "A" || characteristic.charAt(i) > "Z"){
System.out.println(" character number " + i + " is invalid");
progress = false;
}
}
if (characteristic.charAt(3) < "1" || characteristic.charAt(3) > "9")
progress = false;
for (int j = 3; j < 7; ++j){
if (characteristic.charAt(j) < 0 || characteristic.charAt(j) > 9)
progress =false;
}
if (progress == false){
System.out.println("characteristic will have the value null.");
characteristic = null;
}
if (progress == true)
car.setCharacteristic(characteristic);
}
I'm having a problem at the lines "if (characteristic.charAt(i) < "A" || characteristic.charAt(i) > "Z"){"
The compiler is saying "The operator < is undefined for the argument type(s) char, String"
Any help is highly appreciated, thanks.
In Java, you can compare a character (char) to a character, but you can't compare a character to a String. charAt returns a character, so you must compare its result to a character.
These are String
"A" "Z" "1" "9"
And these are characters
'A' 'Z' '1' '9'
You can compare a character to an integer (int), but the result may not be what you want. So in the code below:
for (int j = 3; j < 7; ++j){
if (characteristic.charAt(j) < 0 || characteristic.charAt(j) > 9)
0 and 9 should be change to '0' and '9'.
Note: There is another unrelated logic error in your code:
String characteristic = kb.nextLine();
progress = false;
Shouldn't progress be set to true here?
I would certainly check out the other answers on this page re. character comparisons. However, I would perhaps suggest a different approach given:
starts with two capital letter followed by a number from 1-9 followed
by 4 numbers from 0-9
and investigate regular expressions. Something like:
[A-Z]{2}[1-9][0-9]{4}
would satisfy the above requirement.
Use single quotes for chars, double quotes for Strings.
characteristic.charAt(3) < '1'
there is meaning for single and double quotes in java
And for your situation best suits is a regex
Replace the double quotes with single quotes.
You'll also have to put single quotes around the numbers when comparing them with chars, even though the compiler doesn't complain.
Compare like this
characteristic.charAt(3) < '1'
First, you can achieve this goal with regexp:
[A-Z]{2}[1-9][0-9]{4}
(Read Pattern article to know how to use it).
If you want to do it as you started - use singleqoutes instead of doublequotes with characters. e.g. "a" -> 'a'.
If you want to assign value to char use single quote. If it is a String use double quote
char myChar='a';
String myString="a";
so
characteristic.charAt(3) < "1" should change as characteristic.charAt(3) < '1'
I've got a simple java assignment. I need to determine if a string starts with the letter A through I. I know i have to use string.startsWith(); but I don't want to write, if(string.startsWith("a")); all the way to I, it seems in efficient. Should I be using a loop of some sort?
You don't need regular expressions for this.
Try this, assuming you want uppercase only:
char c = string.charAt(0);
if (c >= 'A' && c <= 'I') { ... }
If you do want a regex solution however, you can use this (ideone):
if (string.matches("^[A-I].*$")) { ... }
if ( string.charAt(0) >= 'A' && string.charAt(0) <= 'I' )
{
}
should do it
How about this for brevity?
if (0 <= "ABCDEFGHI".indexOf(string.charAt(0))) {
// string starts with a character between 'A' and 'I' inclusive
}
Try
string.charAt(0) >= 'a' && string.charAt(0) <= 'j'
char c=string.toLowerCase().charAt(0);
if( c >= 'a' && c <= 'i' )
...
This makes it easy to extract it as a method:
public static boolean startsBetween(String s, char lowest, char highest) {
char c=s.charAt(0);
c=Character.toLowerCase(c); //thx refp
return c >= lowest && c <= highest;
}
which is HIGHLY preferred to any inline solution. For the win, tag it as final so java inlines it for you and gives you better performance than a coded-inline solution as well.
if ( string.toUpperCase().charAt(0) >= 'A' && string.toUpperCase().charAt(0) <= 'I' )
should be the easiest version...
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.