错误:类型不兼容:void无法转换为NumPal

时间:2018-06-23 00:00:39

标签: java constructor main

我已经阅读了许多有关此问题的主题,并且大多数问题似乎都可以通过修复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;
   }
}

如果有人可以分解此错误的含义,将不胜感激!

1 个答案:

答案 0 :(得分:2)

NumPalDriver上的以下行

p = p.next();

期望NumPal类中的next()方法返回NumPal对象(或null)。当前代码不返回任何内容。重写它以返回NumPal

即:

public NumPal next(){ 
    // return a NumPal, possibly following
    // existing code of this method goes here
    return new NumPal(stringCur)
}