Error in my Word program in Java - java

This is my code and it compiles fine but when I try to create a string it says
Error: cannot find symbol - variable racer
public class Word {
private String original;
public Word(String s) {
original = s;
}
public String reverse () {
String reverse= "";
int x = 1;
int length = original.length();
while (length - x >= 0) {
reverse = reverse + original.substring(length -x);
x++;
}
return reverse;
}
public boolean isPalindrome() {
if(original.equals(reverse()))
return true;
else
return false;
}
}

The stated problem is not in the code posted - my guess is irrelephant's comment is correct, ie change new Word(racer) --> new Word("racer").
But I offer this to eliminate any chance of any errors in your code by basically eliminating your code:
public class Word {
private String original;
public Word(String s) {
original = s;
}
public boolean isPalindrome()
return new StringBuilder(original).reverse().toString().equals(original);
}
}
or if you must expose a reverse() method:
public class Word {
private String original;
public Word(String s) {
original = s;
}
public String reverse () {
return new StringBuilder(original).reverse().toString();
}
public boolean isPalindrome()
return reverse().equals(original);
}
}

I don't see the variable racer anywhere, but since you're using reverse inside a method, I'd recommend making it
Most likely, racer was never defined
Either that or the method was called w/o quotes
isPalindrome(racer)//note the lack of quotes
change reverse() to this
private() String reverse () {
String reverse= "";
int x = 1;
int length = original.length();
while (length - x >= 0) {
reverse = reverse + original.substring(length -x);
x++;
}
return reverse;

Related

why I am getting ArrayIndexOutOfBoundsException?

Hi I am unable to know what I am doing wrong.
I have a string which is pass as an argument to a my class.
I have to split that string and assign the respective values to the member variable but it is not working properly.
Here is my class.
package virtusa;
public class pratice {
String getName;
Double getPrice;
int getQuantity;
String temp[] = null;
public pratice()
{
}
public pratice(String rawInput)
{
temp = rawInput.split("$$##",2);
getName = temp[0];
getPrice = Double.parseDouble(temp[1]);
getQuantity =Integer.parseInt( temp[2]);
}
public String getGetName() {
return getName;
}
public Double getGetPrice() {
return getPrice;
}
public int getGetQuantity() {
return getQuantity;
}
}
here is my main class
package virtusa;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String stub = in.nextLine();
pratice temp = new pratice(stub);
System.out.println(temp.getName);
System.out.println(temp.getQuantity);
System.out.println(temp.getPrice);
}
}
My Input = apple$$##12.5$$##9
error i am having -
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at virtusa.pratice.<init>(pratice.java:17)
at virtusa.demo.main(demo.java:12)
String::split take regex as a parameter, so the $ has special meaning. You will need to escape it with a \
One of problems in your code in not escaping special characters as some comments are mentioning. In my opinion clearest solution is to use Patter quote
rawInput.split(Pattern.quote("$$##"), 3);
Other problem is that you clearly need to get there elements since you are trying to get temp[0], temp[1] and temp[2]
So the final code should look something like this
String getName;
Double getPrice;
int getQuantity;
String temp[] = null;
public Practice() {
}
public Practice(final String rawInput) {
temp = rawInput.split(Pattern.quote("$$##"), 3);
getName = temp[0];
getPrice = Double.parseDouble(temp[1]);
getQuantity = Integer.parseInt(temp[2]);
}
public String getGetName() {
return getName;
}
public Double getGetPrice() {
return getPrice;
}
public int getGetQuantity() {
return getQuantity;
}

Backtracking bruteforce Java password cracker

I have this homework assignment to make a recursive method to crack a password of a given length, n (unlimited and unknown!) made of small English letters, a-z ONLY.
Here's the class "Password" that creates a random password:
import java.util.Random;
public class Password {
private String _password = "";
public Password(int length) {
Random generator = new Random();
for (int i = 0; i < length; ++i) {
this._password = this._password + (char) (generator.nextInt(26) + 97);
}
}
public boolean isPassword(String st) {
return st.equals(this._password);
}
public String getPassword() {
return this._password;
}
}
And here is the question in detail:
"You must write a static recursive method,
public static String findPassword(Password p, int length) that "cracks" the code.
Here's an example of a main method:
public class Main {
public static void main(String[] args) {
Password p = new Password(5);
System.out.println(p.getPassword());
System.out.println(Ex14.findPassword(p, 5));
}
}
Important notes:
The method MUST be recursive, without using ANY loops.
You may not use the getPassword method.
If you would like to use a method of the String class, you may only use the following: charAt, substring, equals, length.
You MAY use overloading, but you MAY NOT use other methods. (You cannot use String.replace/String.replaceall)
You MAY NOT use static(global) variables.
You MAY NOT use any Array. "
Here's what I have until now, which clearly doesn't work; :\
public static String findPassword(Password p, int length) {
return findPassword(p, length, "", 'a');
}
public static String findPassword(Password p, int length, String testPass, char charToChange) {
int currDig = testPass.length() - 1;
if (p.isPassword(testPass))
return testPass;
if (length == 0) // There is no password.
return ""; // Returns null and not 0 because 0 is a password.
if (length > testPass.length())
return findPassword(p, length, testPass + charToChange, charToChange);
if (testPass.length() == length) {
//TODO if charToChange is 'z', then make it the one before it '++', and reset everything else to a.
//if (charToChange == 'z') {
// charToChange = 'a';
// String newString = testPass.substring(0, currDig-1) +
// (charToChange++)
// +testPass.substring(currDig+1,testPass.length()-1);
System.out.println("it's z");
// TODO currDig --;
// String newerString = testPass.substring(0, currDig - 1)
// + (char) (testPass.charAt(testPass.length() - 1) - 25);
// currDig--;
}
return "";
}
Thank you very much! much appreciated!
- TripleS

JUnit4 (assertEquals) saying objects are different, when they're the same?

I'm testing my code using JUnit4 to see if an insertion sort of an array of objects (Word(String a, int b)) is correctly sorting the array. The problem I'm having is that when I run JUnit it fails, giving me an error: "expected {One, 1} but was {One, 1}." If I print out both values I'm comparing before I run the test they are also the same. The code is:
package sort;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class InsertionTest {
private Word word1;
private Word word2;
private Word word3;
private Word word4;
private Word wordExpected1;
private Word wordExpected2;
private Word wordExpected3;
private Word wordExpected4;
#Before
public void setUp() throws Exception {
word1 = new Word("One", 1);
word2 = new Word("Two", 2);
word3 = new Word("Three", 3);
word4 = new Word("Four", 4);
wordExpected1 = new Word("One", 1);
wordExpected2 = new Word("Two", 2);
wordExpected3 = new Word("Three", 3);
wordExpected4 = new Word("Four", 4);
}
#After
public void tearDown() throws Exception {
}
#SuppressWarnings("deprecation")
#Test
public void test() {
Word[] wordList = { word3, word2, word4, word1 };
Word[] expected = { wordExpected1, wordExpected2, wordExpected3, wordExpected4 };
Insertion.sortInsert(wordList);
assertEquals(expected, wordList);
}
}
The code for the insertionsort:
package sort;
public class Insertion {
/**
* regular insertion sort
* #param x - the input array containing scores of words that need to be sorted.
*/
public static void sortInsert ( Word[] x) {
int N = x.length;
for (int i = 1; i < N; i++){
int tempScore = x[i].getScore();
String tempWord = x[i].getWord();
int j;
for (j = (i - 1); j >= 0 && tempScore < x[j].getScore(); j--){
x[j + 1].setScore(x[j].getScore());
x[j + 1].setWord(x[j].getWord());
}
x[j + 1].setScore(tempScore);
x[j + 1].setWord(tempWord);
}
}
}
The code for the ADT:
package sort;
public class Word implements Comparable<Word>{
private String word;
private int score;
public Word(String w, int s){
this.word = w;
this.score = s;
}
public int getScore(){
return score;
}
public void setScore(int s){
score = s;
}
public String getWord(){
return word;
}
public void setWord(String w){
word = w;
}
#Override
public int compareTo(Word w){
if ((this.score) > (w.score)) { return 1; }
else if ((this.score) < (w.score)) { return -1; }
return 0;
}
public String toString(){
return ("{" + this.word + "," + this.score + "}");
}
}
Any help would be appreciated, thank you!
You're creating two different objects. Just because their attributes have the same value, they are not necessarily equal. To achive this, you need to override the equals() method in class Word.
Thus, add:
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Word other = (Word) obj;
if (score != other.score)
return false;
if (word == null) {
if (other.word != null)
return false;
} else if (!word.equals(other.word))
return false;
return true;
}
Eclipse provides an easy way to do this (semi-)automatically. Open your Word class, select Source -> Generate hashCode() and equals()...
Select attributes that should be considered when checking two Word objects for equality.
Also, you should oderride hashCode().
Related questions:
Why should I override hashCode() when I override equals() method?
What issues should be considered when overriding equals and hashCode in Java?
By the way:
Might be a copy&paste issue, but implemented methods from interfaces are not being annotated with #Override (as your compareTo() is). #Override annotation would be appropriate for toString() since you override the toSting()-method of class Object.
From #Override Javadoc:
Indicates that a method declaration is intended to override a method declaration in a supertype.
JUnit's assertEquals depends on you correctly implementing Object.equals(Object), which you didn't do. Implement equals(Object) in Word to make this work.
Use Lombok to generate the equal and hashcode method. Then it will work. Your code will also become clean by using Lombok annotations.

recursive expand of strings

I want to create a method which recursively expands the input string with another string.
public class StringTest {
public static String addZeichenkette(String out, int i) {
out += "bla";
if (i > 0) {
i--;
addZeichenkette(out, i);
}
return out;
}
public static void main(String[] args) {
String out = "Hello";
out = addZeichenkette(out, 7);
System.out.println(out);
}
}
The output should be :
Helloblablablablablablabla
instead it is
Hellobla
The main method has to be untouched (except the method calling).
You're ignoring the return from the recursive call.
public static String addZeichenkette(String out, int i)
{
if (i > 0)
{
out += "bla";
i--;
out = addZeichenkette(out, i);
}
return out;
}
Alternatively, you could just return the result addZeichenkette(out, i);, but both ways are fine.
As you pointed out, you would need to modify it to avoid adding i+1 bla's. Since when i = 0, we don't want any bla's to be added, we instead need to check for this.
To do this, I moved the concatenation of the bla into the condition.
You need to return the accumulated (recursed) string:
return addZeichenkette(out, i);
not just the one where i == 0.
public static String addZeichenkette(String out, int i) {
return i > 0 ? addZeichenkette(out + "bla", --i ) : out;
}

Java contains a string or not?

http://codingbat.com/prob/p126880
Given two strings, return true if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: str.toLowerCase() returns the lowercase version of a string.
I cannot get when it is true, it always gives false.
public boolean endOther(String a, String b)
{
//variables
a.toLowerCase();
b.toLowerCase();
String f1="";
String f2="";
int d=0;
int sum=0;
//Program code;
if(a.length()-b.length()>0)
{
(f1).equals(a);
(f2).equals(b);
d=a.length();
}
else if(a.length()-b.length()<0)
{
(f1).equals(b);
(f2).equals(a); //gett**ing bigger and lower String**
d=b.length();
}
else if((a).equals(b))
sum++;
// I think problem is because it is not enter the for.
for(int i=0; i>d; i++)
{
if((f1.substring(i,i+f2.length())).equals(f2))
sum++;
}
if(sum>0)
return true;
else
return false;
}
This is a working example of what you are trying to achieve to test in your Java IDE like Netbeans or Eclipse whatever. This is really simple, the String object has an endsWith method so why try to invent something yourself.
If you have any troubles reading this code hit me up, should be quite straight forward. You will just have to convert your string to lowercase, that's for you to add.
public class StringEnds {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.printf("String a: ");
String a = scanner.next();
System.out.printf("String b: ");
String b = scanner.next();
// Compare a and b
if (endsWith(a, b)) {
System.out.printf("Succes\n");
} else {
System.out.printf("Fail\n");
}
}
public static boolean endsWith(String firstString, String secondString) {
return firstString.endsWith(secondString) || secondString.endsWith(firstString);
}
}
Here's your codebat solution (it is quite short):
public boolean endOther(String a, String b) {
return a.toLowerCase().endsWith(b.toLowerCase()) || b.toLowerCase().endsWith(a.toLowerCase());
}
This is my answer. I tried both ways, hope it helps.
public boolean endOther(String a, String b) {
int small = Math.min(a.length(), b.length());
if (a.length()==b.length() && a.equalsIgnoreCase(b)) {
return true;
}
if (small==a.length()) {
if (b.substring(b.length()-small).equalsIgnoreCase(a)) {
return true;
}
// from here is the toLowerCase() method.
a = a.toLowerCase();
b = b.toLowerCase();
} else if (small==b.length()) {
if (a.endsWith(b)) {
return true;
}
}
return false;
}

Categories