简体   繁体   English

Java中的Word程序错误

[英]Error in my Word program in 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 这是我的代码,可以正常编译,但是当我尝试创建字符串时显示错误:找不到符号-变量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") . 声明的问题不在发布的代码中-我的猜测是irrelephant的注释正确,即更改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: 或者,如果您必须公开一个reverse()方法:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM