The program is suppose to check if a string is consecutive including string such as zab and 901234. I wrote and exception to each so I can skip over 90 or za if they appear. Unfortunately I can't seem to get into the if block of code... I'm not sure why. If someone can help me get into this 901 it would be much appreciated.
for (int i=0; i<s.length()-1; i++){
if (s.charAt(i) == 9 && s.charAt(i + 1) == 0) {
System.out.println("in");
}
}
Remember, integers get converted to characters through the ASCII table, so you want the characters '9' and '0'
Your original code was actually looking for the null (0) and backspace (9) characters. More info on the ASCII table here: ASCII Table
for (int i=0; i<s.length()-1; i++){
if (s.charAt(i) == '9' && s.charAt(i + 1) == '0') {
System.out.println("in");
}
}
You need to test for charachers:
if (s.charAt(i) == '9' && s.charAt(i + 1) == '0') {
Related
I'm supposed to create a program that finds the longest palindrome in a DNA string. Unlike a regular palindrome program, this one requires A to match with T and C to match with G (so instead of 1221 we'd have TCGA for example). After trying myself I did find a very good program for the normal palindrome problem, the one on this website:
http://www.journaldev.com/530/java-program-to-find-out-longest-palindrome-in-a-string
I then tried to modify it to fit my needs. Basically the changes I made were the following:
Instead of those strings shown in the example, I read a string from the argument line. The string is the following DNA sequence (although I tested the program with only parts of it):
http://introcs.cs.princeton.edu/java/31datatype/genomeVirus.txt
Instead of the command
while (left >= 0 && right < s.length()
&& s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
I did:
while (left >= 0 && right < s.length()
&& s.charAt(left) == 'A' && s.charAt(right) == 'T' || s.charAt(left) == 'T' && s.charAt(right) == 'A'
|| s.charAt(left) == 'G' && s.charAt(right) == 'C' || s.charAt(left) == 'C' && s.charAt(right) == 'G')
{
left--;
right++;
(Full code below)
However, when I try this program on a string, I always get the error:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at LongestPalindrome.intermediatePalindrome(LongestPalindrome.java:17)
at LongestPalindrome.longestPalindromeString(LongestPalindrome.java:26)
at LongestPalindrome.main(LongestPalindrome.java:5)
I just don't get it! I don't realize how I'm getting out of the string, when I try the original program I linked to, it always works with no matter which string. I feel like I'm doing everything correctly, simply replacing the == command with various scenarios that should make sense.
I figured it might have something to do with
return s.substring(left+1, right);"
I tried to take the +1 away but it seems to ruin the whole deal. I just don't realize how I'm going out of the string, since it worked perfectly before my adjustments.
Any help would be greatly appreciated! Below is the code!
public class LongestPalindrome {
public static void main(String[] args) {
String gen = new String(args[0]);
System.out.println(longestPalindromeString(gen));
}
static public String intermediatePalindrome(String s, int left, int right) {
if (left > right) return null;
while (left >= 0 && right < s.length()
&& s.charAt(left) == 'A' && s.charAt(right) == 'T' || s.charAt(left) == 'T' && s.charAt(right) == 'A'
|| s.charAt(left) == 'G' && s.charAt(right) == 'C' || s.charAt(left) == 'C' && s.charAt(right) == 'G')
{
left--;
right++;
}
return s.substring(left+1, right);
}
// O(n^2)
public static String longestPalindromeString(String s) {
if (s == null) return null;
String longest = s.substring(0, 1);
for (int i = 0; i < s.length() - 1; i++) {
//odd cases like 121
String palindrome = intermediatePalindrome(s, i, i);
if (palindrome.length() > longest.length()) {
longest = palindrome;
}
//even cases like 1221
palindrome = intermediatePalindrome(s, i, i + 1);
if (palindrome.length() > longest.length()) {
longest = palindrome;
}
}
return longest;
}
}
You are calling it with right == 0. You need to change the first call to:
String palindrome = intermediatePalindrome(s, i, i+1)
Operator precedence problem. You've added some || conditions which are also evaluated even if the range checks fail. It should be:
while (left >= 0 && right < s.length()
&& (s.charAt(left) == 'A' && s.charAt(right) == 'T'
|| s.charAt(left) == 'T' && s.charAt(right) == 'A'
|| s.charAt(left) == 'G' && s.charAt(right) == 'C'
|| s.charAt(left) == 'C' && s.charAt(right) == 'G'))
Note the parentheses around the entire second operand of the second &&.
So i have a string in military time format : "1532" corresponding to 3:32pm.
I'm trying to write a method to check if each digit in time string is an appropriate digit. So the first element cannot be greater than 2 or equal to 0, and so forth. Currently, my code doesn't run past the second log statement and I'm hoping you guys could help!
cheers!
String mOpen = "1532";
Log.d("hoursTesting","pass1, length is > 2");
if(mOpen.getText().length() == 4)
{
Log.d("hoursTesting","pass2, length is == 4");
char[] tempString = mOpen.getText().toString().toCharArray();
if(tempString[0] != 0 && tempString[0] < 3)
{
Log.d("hoursTesting","pass3, first index is != 0 and < 3");
if(tempString[0] == 1)
{
Log.d("hoursTesting","pass4, first index is 1");
if(tempString[2] <= 5)
{
Log.d("hoursTesting","pass5, third index is <= 5, success!");
}
}
else //tempString[0] is equal to 2
{
Log.d("hoursTesting","pass4, first index is 2");
if(tempString[1] < 4)
{
Log.d("hoursTesting","pass5, second index is <3");
if(tempString[2] <= 5)
{
Log.d("hoursTesting","pass6, third index is <= 5, success!");
}
}
}
}
}
tempString contains characters, not numbers.
i.e. '0' not 0 etc.
Easiest fix is to compare characters e.g. tempString[0] == '1' Alternatively, you can do something like int digit1 = tempString[0] - '0'; - but that kind of assumes you already know you just have digits in the string.
Note that cos of those clever ASCII guys and their tricky character set '0' < '1' < '2' etc, so you can still say if (str[0] < '2') etc. You just need to be a bit careful that you are only dealing with digits.
Personally I'd convert the first 2 chars to a number and the second 2 chars to a number and then just check 0 <= number1 <= 23 and 0 <= number2 <= 59.
You are comparing char with int here:
if(tempString[0] != 0 && tempString[0] < 3)
It should work like this:
if(tempString[0] != '0' && tempString[0] < '3')
I would substring the hours and minutes components and then check to see if each one be in range:
public boolean isTimeValid(String mOpen) {
int hours = Integer.parseInt(mOpen.substring(0, 2));
int minutes = Integer.parseInt(mOpen.substring(2));
if ((hours >= 0 && hours <= 24) && (minutes >= 0 && minutes <= 59)) {
return true;
}
else {
return false;
}
}
I got a school-project where I was given this information:
for i=1 to m
if c_i is an operand: Transfer c_i to output.
if c_i is a left parentheses: Push c_i to tmp.
if c_i is a right parentheses: Pop elements from tmp and transfer
them to output until a left-parentheses
is met. Pop left-parentheses.
if c_i is an operator: Let the top tmp element be t. Pop and
transfer elements from tmp to output
until:
p(t) < p(c_i) or
t is a left-parentheses or
tmp is empty.
Push c_i to tmp.
Transfer the remaining elements in tmp to output.
I have been doing exactly these steps, but my output only gets right som times. I guess that Im thinking wrong somewhere around the if statement with the operators. I've constantly been debugging for 2 days now, and I just cant find the solution.
I would be very pleased if someone would like to check my code. The operatorCheck function is made for solving this: "We use the subroutine p to specify the priorities of the operators:
p(+) = 0,
p(−) = 0, p(∗) = 1, p(/) = 1
. This means that addition and subtraction have
lower priority compared to multiplication and division."
Code: http://pastebin.com/TA7UGiGc
Thank you!
You're looping and removing the first letter from tmp without getting the next letter to compare with in the while loop, therefore you need to get a new character inside the while loop.
The substring is also removing the wrong characters from tmp, it should keep everything except the first letter and that's accomplished with tmp.substring(1, tmp.length())
I have fixed that block of code below:
else if (character == '+' || character == '-' || character == '*' || character == '/'){
while (true) {
char t = tmp.length() > 0 ? tmp.charAt(0): ' ';
if (operatorCheck(t) < operatorCheck(character) || t == '(' || tmp.length() < 0) {
break;
}
output += t;
tmp = tmp.substring(1, tmp.length());
}
tmp = character + tmp;
}
Marco, in your code, the line 42
while (tmp.length() > 0 && !(operatorCheck(t) > operatorCheck(character)) && t != '(')
you have to change > with <
In the algorithm, the exit conditions are
tmp.length()==0 || p(t) < p(c_i) || t=='('
Since it's a while you have to negate that
!(tmp.length()==0 || p(t) < p(c_i) || t=='(')
===
(tmp.length()>0 && p(t) >= p(c_i) && t!='(')
=== (to write it with ! as you did)
(tmp.length()>0 && !(p(t) < p(c_i)) && t!='(')
Besides this, Dante is right about using stacks. If you want to avoid the autoboxing problem you can make your own primitive stack class for char
So I am doing some practice problems for an upcoming exam and one of the problems is posing a bit of a challenge to me.
The problem states that our code should take a string that has been encoded and decode it. It must work as follows:
Each letter is decoded using the letter immediately before it in the alphabet ("b" becomes "a", "c" becomes "b" ect.)
"a" becomes "z".
each digit works the same way, 8 becomes 7, 5 becomes 4.
0 becomes 9.
characters neither letters nor digits are unchanged.
THE ONLY JAVA METHOD I CAN USE IS IO
Ex:
NFFU NF BU 23 JO UIF CFMM UPXFS
meet me at 12 in the bell tower
heres my current code, i cannot decide whether to use for loops or not. TBH I am not really sure how to tackle this.
public class prb1 {
public static void main(String[] args) {
char letter[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int num[]={0,1,2,3,4,5,6,7,8,9};
System.out.println("Enter Message");
String mssg=IO.readString();
for(char i=0; i<letter.length; i++){
System.out.print(letter[i]--);}
for(int j=0; j<num.length; j++){
System.out.print(num[j]--);
}
}
}
The basic is like this. But this doesn't account yet for the a => z conversion.
String cypher ="ABCDEF";
String plain = "";
for (char c : cypher.toCharArray())
plain += (char) (c - 1);
System.out.println(plain);
With the modulo A => Z, it looks like this:
int A = 'A';
plain += (char) (((c - A - 1 + 26) % 26) + A);
The +26 is needed because java says -1 % 26 == -1 instead of 25.
So this just works for A-Z, but you can easily modify it to work for wider ranges.
You can use a loop to iterate through each character of the message and subtract one from its ascii code if its not a space, an a, or an A:
String message = "NFFU NF BU 23 JO UIF CFMM UPXFS";
String result = "";
for (char thisChar : message.toCharArray()) {
if (thisChar == ' ') {
result += " ";
} else if(thisChar == 'a') {
result += 'z';
} else if (thisChar == 'A') {
result += 'Z';
} else
result += (char)(thisChar - 1);
}
}
System.out.println(result);
Alternatively, you could do:
String message = "NFFU NF BU 23 JO UIF CFMM UPXFS";
String result = "";
for (int i = 0; i < message.length(); i ++) {
char thisChar = message.charAt(i);
if (thisChar == ' ') {
result += " ";
} else if(thisChar == 'a') {
result += 'z';
} else if (thisChar == 'A') {
result += 'Z';
} else
result += (char)(thisChar - 1);
}
}
System.out.println(result);
Technically,
else if(thisChar == 'a') {
result += 'z';
} else if (thisChar == 'A') {
result += 'Z';
}
could be shortened to:
else if(thisChar == 'a' || thisChar == 'A') {
result += (char)(thisChar + 25);
}
I'm having a bit of trouble with detecting a CHAR in an if statement.
I have a score integer, which i made in to a String, and from the string, i made a char Array.
My problem is, that when i try to detect what number the char is, it returns the "Error.png".
Please help me :)
code:
scoreString = "" + score;
System.out.println(scoreString + " - " + scoreString.length());
scoreA = scoreString.toCharArray();
for(int counter = 0; counter < scoreString.length(); counter++){
Texture drawT;
if(scoreA[counter] == 0) drawT = i0;
else if(scoreA[counter] == 1) drawT = i1;
else if(scoreA[counter] == 2) drawT = i2;
else if(scoreA[counter] == 3) drawT = i3;
else if(scoreA[counter] == 4) drawT = i4;
else if(scoreA[counter] == 5) drawT = i5;
else if(scoreA[counter] == 6) drawT = i6;
else if(scoreA[counter] == 7) drawT = i7;
else if(scoreA[counter] == 8) drawT = i8;
else if(scoreA[counter] == 9) drawT = i9;
else drawT = error;
MainClass.batch.draw(drawT, 5 + (9 * counter), 95);
}
scoreA[counter] == 1 compares a character to the numerical value of 1, which is not correct. '1' is not the same thing as 1. In fact, '1' is actually equal to 31 in hex. Use something like:
if(scoreA[counter] == '0') drawT = i0;
else if(scoreA[counter] == '1') drawT = i1;
//continue on
I obviously included a short snippet but it should be enough.
You want character literals.
You need to write
if(scoreA[counter] == '1')
Your mistake is thinking that the char representation for numbers are the same as the numbers themselves - they're not. chars represent ASCII characters (strictly speaking unicode but for this purpose we can just assume ASCII), so the code of the character 0 is NOT the number 0. To fix the problem you can just use char literals in your comparisons:
if(scoreA[counter] == '0') drawT = i0;
else if(scoreA[counter] == '1') drawT = i1;
... etc
Always you have to set character literals with in the single coats
i.e.
scoreA[counter] == '0'