我已经阅读了许多关于这个问题的线程,大多数似乎都可以通过修复 main 方法来解决。但是,任务的一部分是我们不能更改NumPalDrvier。 我还能如何解决这个问题,因为我不完全理解它?
这是给定的主代码:
import javax.swing.JOptionPane;
public class NumPalDriver {
public static void main(String[] args){
String start = JOptionPane.showInputDialog("Enter a number: ");
System.out.println("start value ["+ start + "]");
NumPal p = new NumPal(start);
int ctr = 0;
while (!p.pal() && (ctr < 10)){
System.out.println(p.toString());
System.out.print("new sum: ");
System.out.println(p.getCur()+" + "+p.getRev()+ " = " +
(p.getCur()+p.getRev() ));
p = p.next();
ctr++;
}
System.out.println("final value: " + p.getCur());
System.out.println("number of steps: " + ctr);
}
}
我的代码使主要可能:
public class NumPal{ //header
private long numRev; //initializes variables
private long numCur;
private String stringRev;
private String stringCur;
public NumPal(String stringCur){//constructor
this.stringCur = stringCur;
}
public boolean pal(){
if (stringCur == stringRev){
return true;}
else {
return false;}
}
public String reverseString (String input){ //creates reverse version of string
int length = input.length();
String stringRev = "";
for(int j = 0; j <= length; j++){
stringRev = input.charAt(j) + stringRev;
}return stringRev;
}
public void next(){ //where the error is
stringRev = reverseString(stringCur);
numRev = Long.parseLong(stringRev);
numCur = Long.parseLong(stringCur);
numCur = numCur + numRev;
stringCur = Long.toString(numCur);
}
public String getCur(){ // returns current string
return stringCur;
}
public String getRev(){ // returns reverse string
return stringRev;
}
}
如果有人可以分解此错误的含义,将不胜感激!
NumPalDriver 上的以下行
p = p.next();
期望 NumPal类中的 next(( 方法返回 NumPal 对象(或 null(。当前代码不返回任何内容。重写它以返回一个数字宝
即:
public NumPal next(){
// return a NumPal, possibly following
// existing code of this method goes here
return new NumPal(stringCur)
}