For a class I am taking, I am to create a program that tests whether a string is a palindrome. We were supposed to just use an 8 character string every time and hard-code it that way, but I wanted to get above and beyond and make something to test any string. Unfortunately, this code seems to aways return true, and I'm honestly not sure why.
public static boolean palindromeTest(String input){
//This portion declares variables necessary for testing, and modifies them if necessary.
int inputLength=input.length();
char[] Chars=input.toCharArray();
for(int j=0; j<inputLength; j++){
Character.toLowerCase(Chars[j]); //makes all characters in input lower case
//This portion performs the palindrome test
}
if(inputLength%2>0){ //if length is odd
inputLength=(inputLength-1)/2;
for(int i=0; i>0; i++){
if(Chars[i]!=Chars[inputLength-i]) //tests equality first and last in pairs via for loop
return false; //break;
}
}else{ //if length is even
inputLength=(inputLength)/2;
for(int i=0; i>0; i++){
if(Chars[i]!=Chars[inputLength-i]) //tests equality first and last in pairs via for loop
return false; //break;
}
}
return true; //if all tests are passed, input is indeed a palindrome
}
it is because of
for(int i=0; i>0; i++){
the code inside the for loop will never be executed as i is never greater than 0
Edit:
Moreover
if(charArray[i]!=charArray[inputLength - i])
is kinda wrong, cuz lets say your string is madam, inputLength = inputLength-1 makes the above condition to check "m" and "d" which not how it should work
the correct solution would be
inputLength = inputLength / 2;
int j= input.length()-1;
for(int i =0; i< inputLength; i++, j--) {
if(charArray[i]!=charArray[j]) {
return false;
}
}
the palindrome test method using for loop and char array is as follows:
public static boolean palindromeTest(String input){
char[] Chars=input.toCharArray();
for(int i=0,j=Chars.length-1;i<j;i++,j--){
if(Chars[i]!=Chars[j]){
return false;
}
}
return true;
}
Related
public static int StringInString(String one, String two) {
if(one==null||two==null||one.equals("")||two.equals("")){
return 0;
}
else{
int x=one.length(),y=two.length(),sum=0,i=0,j=0;
char[] onee=one.toCharArray();
char[] twoo=two.toCharArray();
while(i<x){
while(j<y){
if(onee[i]==twoo[j]){
i++;
j++;
}
else{
if(j==0){
i++;
}
else{
j=0;
i++;
}
}
}
sum++;
i=i-y+1;
j=0;
}
return sum;
}
}
public static void main(String[] args){
int sum;
sum = StringInString("salamsal","sal");
System.out.println(sum);
}
hello I dont know why this ERROR apear?! please HELP me;
this code want count the similar text in two stringsa
and the result of this code should be = 2.
When you are inside the second "while" cycle, even if i > x, the cycle continues as long as j < y. So when it happens that i++ in the second cycle makes i become greater than x-1, and j is still less than y, in the first "if" (always inside the second while cycle) the program tests if onee[8] == twoo[0], and since onee[8] doesn't exist (because the indexes of "salamsal" go from 0 to 7) it shows the error that the index is out of the array bounds. To solve the error you should check for the value of i inside the second cycle, because it may happen that i++ makes this index become greater than x-1, where x is, as you declared, the length of the first string.
I am trying to pass a word to my findWord method which checks a 2d array of stype String[][] "a" for said word. Row and column are the dimensions of "a". I am not checking diagonal or reverse, only forwards. I believe that nearly if not all of my logic is correct, but I think I'm getting a bounds error. No error is being thrown, but the code just isn't working properly by returning false in random cases that it should return true. Code compiles and runs fine. (i.e it checking past the amount of columns that exist).
public boolean findWord(String word) {
int cL = column;
for(int i = 0; i < row; i++) {
for(int j = 0; j < column; j++) {
if(a[i][j].equals(word.substring(0,1))) {
int c = 1;
int parameter = j + word.length();
if(parameter <= cL) {
for(int k = j; k < parameter; k++) {
if(!a[i][k].equals(word.substring(c,c+1)))
return false;
c++;
}
return true;
}
} else {
return false;
}
}
}
return true;
}
I have run a few test cases. I have not yet found a case where your method returns true despite the word being in the array.
The flaws I have seen in your code are:
You start looking in a[0][0]. If the string found here isn’t equal to the first letter of your word, you immediately return false without looking any further.
Say that the first letter of the word does match a[0][0]. Now you set c to 1, but since i and k are 0, you now compare the second letter of the word to a[0][0]. That is unlikely to match. It only does of the word begins with the same letter twice.
Finally, I did manage to get a StringIndexOutOfBoundsException, namely by searching for aa in a row containing a, b, c. Second time through the innermost loop c is 2, and you therefore try to take out the substring between indices 2 and 3 of a word that has length 2.
You’ve got some fixing to do. Enjoy your work.
first time posting here, I have this problem:
Write a static method named mostBowlsFull, to be added to the Bowl class, which is passed an array of Bowl objects, and returns true if a strict majority of the Bowls in the array are not empty. Thus if the array consists of 11 bowls and 6 are not empty, your method should return true, but if the array consists of 12 bowls and 6 (or fewer) are not empty, your method should return false.
we are given the class here:
https://cesd12.cs.umass.edu/owlj/servlet/ContentFileServer?ID=10778&ManuallyGraded=0&SecureID=2084635103&Server=owl-ijava31haverhillhs&TsActn=1422069785&datasrc=OwliJava31HaverhillHS&fileRequestID=4147
Not sure if it is accessible or if you must be logged on to the service :/
Anyways, this is the code I have
`public static boolean mostBowlsFull(Bowl bowls[]){
int count = 0;
for(int j = 0; j < bowls[].length(), j++){
if(bowls[j].getEmpty == true){
count++;
}
}
if(count > (bowls[].length()/2)){
return true;
}
}`
I am getting for feedback:
The system has detected compilation errors. This could be caused by:
Missing semicolon ; at the end of a statement.
Unclosed braces {}.
Unclosed parentheses ().
Unterminated string literals "".
Invalid method signature.
Missing return statement.
Redeclared variable or data member.
etc.
Any noticeable errors?
EDIT: Alright, so after review I have
public static boolean mostBowlsFull(Bowl bowls[]){
int count = 0;
for(int j = 0; j < bowls.length; j++){
if(bowls[j].getEmpty() == true){
count++;
}
}
if(count > (bowl.length/2)){
return true;
}
}
Still receiving the same message, although I do understand everything that was pointed out, thank you.
It will be easier and less time taking for you to use an IDE and resolve compilation errors.
I see two errors in your for loop:
for(int j = 0; j < bowls[].length(), j++){
use of comma instead of semicolon. for loop syntax is
for (initialization; termination; increment) {
statement(s)
}
Also length is a property for arrays and not a method. So use bowls.length instead of bowls[].length. Also not that you don't need [] while using length.
If you're trying to get the length of bowls, use bowls.length, not bowls[].length().
Also, in your for loop you need a semi-colon in between all three statements:
for(int j = 0; j < bowls.length; j++){ ... }
public static boolean mostBowlsFull(Bowl bowls[]){
int count = 0;
boolean ret=false;
for(int j = 0; j < bowls.length; j++){
if(bowls[j].getEmpty() == false){
count++;
}
}
if(count > (bowls.length/2)){
ret=true;
}
return ret;
}
I've been at this for a while, but as the title says, I'm trying to create a method that will compare each letter to the letter after it and see if the word is ascending. The method should then return a boolean value. But when it's implemented in my code, it will fail with:
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(Unknown Source)
and multiple other lines of error code.
Here's my source code:
public static boolean ascending(String word){
int i = 0;
boolean ascend;
do {
if (word.charAt(i) <= word.charAt(i+1))
ascend = false;
else
ascend = true;
} while (i <= word.length());
i = 0;
return (ascend);
}
I can't see where I'm going wrong?
condition should be
i < word.length()-1
and the i = 0; at the end should be in side the loop as i++, else it will be infinite loop.
also, you have actually put the reverse check. once you fix ArrayIndexOutOfBoundsException you will return false for ascending string and true otherwise
public static boolean ascending(String word){
if(word == null || word.length <2) return false;
int i = 0;
boolean ascend = false;
while(i < word.length()-1){
if (word.charAt(i) <= word.charAt(i+1))
ascend = true;
else{
ascend = false;
break;
}
i++;
}
return (ascend);
}
In pseudo code:
take the first letter (F) => store it
take the next letter (N) => check against first => stop here if not OK
is there another next letter => stop here if not
update first letter (F) with next letter (N)
repeat starting from 2
Few things needs to be fixed here:
You need to increment "i" to traverse through the word.
Restrict your while loop till (i < word.length() )
You may break at any point when you find ascend is false. No need to continue with the looping.
I would not use a do while because there is an opportunity to run this on an empty string causing it to crash. I would instead use a regular while and at the beginning test for while (i < word.length()-1). You never want to test past the end of the string. You always want to check to see for a string length of n that charAt(n-1) < charAt(n). Also I don't see an incrementer to increase the value of i. Loop will never continue on to the next letter and will run forever.
public static boolean ascending(String word){
int i = 0;
boolean ascend;
while (i < word.length()-1)
{
if (word.charAt(i) <= word.charAt(i+1))
ascend = false;
else
ascend = true;
i++;
}
i = 0;
return (ascend);
}
Do not use do-while loop. Even if you do you need to run some checks beforehand to make sure your word has length more than 1 otherwise your code will raise an IndexOutOfBounds Exception. If you insist on using it, change your condition to i
Here is a working code example:
public boolean isAscending(String word){
if (word==null || word.length==0){
return false;
}
for (int i=1; i<word.length(); i++){
if (word.charAt(i) < word.charAt(i-1))
return false;
}
return true;
}
I'm currently working on a project for a class to create a TextLine class that represents the a line of text that must be represented as an array of characters. I am not allowed to represent the TextLine object by using the string class indirectly or directly in any way, however, I can use it to work with the parameters.
For one of the methods, I am supposed to take in a string as an argument of a parameter, which is also a fragment to the TextLine object, and then return the index position of the first occurrence of the fragment in this TextLine, or -1, if the fragment is not found.
Right now, I'm trying to figure out the indexOf method, but my problem is that my method only checks for a starting point once. So if the letter of the TextLine object doesn't match the letter of the fragment the first time, but there is another match somewhere else in the object, the method doesn't check for that starting point.
For example, lets say I enter penplay as the TextLine, then I enter play as the fragment. Clearly, there is an occurrence of play in the TextLine, but what my indexOf method does, is that it checks the first p from penplay at index 0, then continues to see if the following letters match for the length of play, and if it doesn't, it returns -1. Any idea how I could allow the algorithm to keep searching for another starting point?
This is what I have for my code:
public int indexOf(String fragment){
char[] temp = fragment.toCharArray();
int j = 0;
for(int i = 0; i < someText.length; i++){
while(someText[i] == temp[j]){
for(j = 1; j < temp.length; j++){
if(temp[j] != someText[i+j]){
return -1;
}
}
return i;
}
}
return -1;
}
You're special-casing the first character, when there's no need to. Basically you need to say:
For each potential starting character...
Does the whole of fragment match, starting at that candidate position?
So something like:
// Only deal with *viable* starting points
for (int i = 0; i < someText.length - temp.length; i++) {
boolean found = true;
for (int j = 0; j < temp.length && found; j++) {
if (temp[j] != someText[i + j]) {
found = false;
}
}
if (found) {
return i;
}
}
return -1;
This can be refactored by extracting the inner loop:
for (int i = 0; i < someText.length - temp.length; i++) {
if (textMatches(temp, i)) {
return i;
}
}
return -1;
...
// TODO: Javadoc to explain parameters :)
private boolean textMatches(char[] chars, int startingIndex) {
for (int i = 0; i < chars.length; i++) {
if (chars[i] != someText[i + startingIndex]) {
return false;
}
}
return true;
}
The way you have it set up seems suitable as a kind of doesStringExistAtIndex(j, fragment) function. Since that returns -1 if the string doesn't exist at the first index, you could do something like this:
//assuming that "this" is the subject that you are searching in
public int indexOf(String fragment){
for(int i=0; i<this.length; ++i){
if(doesStringExistAtIndex(i, fragment))
return i;
}
return -1;
}
Not sure if this is what you wanted, but I basically wrote up an indexOf method. I did some testing and it seemed to work just fine in some tests I did. Of course, its going to look different because I wanted to make testing easier, but it should be 30 seconds or less of converting if you decide to use it.
public int indexOf(String fragment, String source)
{
char[] temp = fragment.toCharArray();
char[] someText = source.toCharArray();
outer : for(int i = 0; i <= someText.length - temp.length;i++) //stops looping because why loop after the fragment is longer than the source we have left when its impossible to find
{
if(someText[i] == temp[0]) //if the first characters are the same
{
int q = 0;
while(q < temp.length) //loop through the fragment
{
if(someText[i+q] != temp[q]) //if the characters are not the same, stop, and go to the next character of the source. Don't return anything
{
continue outer; //continues the loop labeled 'outer' (e.g. outer : for(...) )
}
q++; //increment index since they both match
}
return i; //fragment and some part of the source matched since it reached here. Return the index of the first character
}
}
return -1; //reached here because nothing was found :( return -1
}
EDIT 0 Added line comments