1

每次我尝试启动我的代码时,我总是遇到同样的错误:

 java.lang.NumberFormatException: For input string: "x"
 at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
 at java.lang.Integer.parseInt(Integer.java:492)
 at java.lang.Integer.parseInt(Integer.java:527)
 at Variable.<init>(Variable.java:17)
 at Main.main(Main.java:4)`

我也放了我的代码。你能帮我理解什么是错的吗?

public class Main {

public static void main(final String[] args) { 
    final Node expression =
      new Plus(
        new Minus(
          new Plus(
            new Variable("x"),
            new Literal(2)
          ),
          new Variable("y")
        ),
        new Minus(
          new Literal(4),
          new Variable("z")
        )
      );
    // an interpreter would just evaluate the expression:
    System.out.println("Expression is: " + expression);

    // a compiler would compile the expression into a program
    System.out.println("Compiling expression...");
    final Program program = new Program();
    expression.generateCode(program);
    System.out.println("Resulting program:\n"+program);

    // and, later, that program can then be executed after the variables have been assigned
    // First assignment of variables
    VariableSpace variables = new VariableSpace();
    variables.store("x", 5);
    variables.store("y", 7);   
    variables.store("z", 1);
    System.out.println("For x = 5, y = 7 and z = 1 the program executes and returns:");
    int resultOfExecution = program.execute(variables);
    System.out.println(resultOfExecution);

    // Second assignment of variables
    variables.store("x", 11);
    variables.store("y", 3);
    variables.store("z", 2);
    System.out.println("For x = 11, y = 3, and z = 2 the program executes and returns:");
    resultOfExecution = program.execute(variables);
    System.out.println(resultOfExecution);        
}

public class Variable extends Node
{
    String variable;
    int value;
    /**
    * Constructor for objects of class Variable
    */
    public Variable(final String variable)
    {
        this.variable = variable;
        int value = Integer.parseInt(variable);
    }

    public void generateCode(final Program program) {
        program.append(new ILOAD(value));
    }

    /**
     * Return a int representing this expression
     * (e.g., new Literal(19).toint() is "19").
     */
      public String toString() {
      return "" + value;
      }
    }

import java.util.ArrayList;


/**
 * A Node in an abstract syntax tree (AST)
* for a very simple expression language.
* The language only supports the following subtypes of Nodes:
* <ul>
* <li>integer values (class Literal)
* <li>integer variables (class Variables)
* <li>the integer + operator (class Plus)
* <li>the integer - operator (class Minus)
* </ul>
* It does not support types other than integers.
*/

public class Node {

/**
 * Compile this AST into an IJVM program:
 * Append instructions to the given Program
 * such that the instructions, when executed
 * produce the same value 
 * as is produced by a call to evaluate(). 
 */
public void generateCode(Program program) {
}

/**
 * Generate a string-representation of the subtree.
 * When you implement this method in subclasses,
 * where possible use recursive calls to left.toString() and
 * to right.toString() to do this.
 */
public String toString() {
    return null;
}

}

public class ILOAD extends Instruction
{
private final int value;

public ILOAD(final int value)
{
    this.value = value;
}

public void execute(Storage storage) {
    storage.getStack().push(value);
}

/**
 * Produce a human-readable String-representation of this instruction.
 */
public String toString() {
    return "ILAOAD " + value;  
}

}

import java.util.*;

/**
* A space that stores the variables during the execution of the IJVM/Java bytecode.
*/
public class VariableSpace {

private HashMap<String, Integer> value;

public VariableSpace() {
    value = new HashMap<String, Integer>();
}

public void store(String name, int value) {
    this.value.put(name, value);   
}

public int load(String name) {
    return value.get(name);
}

}

我遇到的问题是在变量类中,我尝试将字符串转换为整数,因为 ILOAD 类需要一个整数。如果代码太长,我很抱歉,但是这些类是相互链接的。希望你能帮助我

4

4 回答 4

2

查看Integer的文档。

根据那些Integer.parseInt(String s)

抛出 NumberFormatException - 如果字符串不包含可解析的整数

从一个不包含任何内容的字符串中解析一个整数正是您在这个类的构造函数中尝试做的事情Variable......

public Variable(final String variable)
{
    this.variable = variable;
    int value = Integer.parseInt(variable);
}

...当你像这样调用它时。

new Variable("x")
于 2014-05-10T11:36:51.597 回答
1

错误信息很清楚

java.lang.NumberFormatException: For input string: "x"
 at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
 at java.lang.Integer.parseInt(Integer.java:492)

您正在尝试在 parseInt() 方法中将字符串“x”转换为 Integer,可能在这部分

public Variable(final String variable)
    {
        this.variable = variable;
        int value = Integer.parseInt(variable);
    }
于 2014-05-10T11:37:24.760 回答
1

您正在尝试将“x”解析为整数。你认为可能吗?绝对没有!这就是它抛出 NumberFormatException 的原因

阅读有关NumberFormatException的信息

于 2014-05-10T11:38:05.373 回答
1

你没有发布类的代码VariableSpace,所以我假设它是一个包含每个变量值的地图。

在 Variable 的构造函数中,您试图将变量名称解析为 int ,但由于 x 不代表整数x而失败 a 。NumberFormatException

您想要做的实际上是从中检索值VariablStore

int value = variablStore.getValue(variable);

为此,VariablStore需要从类访问实例Varaiable。目前它在 main 方法中是本地的。

编辑

看到整个代码后,这里是您需要的更改:

加载类

/**
 * ILOAD instruction gets the valiable name for later retrieving of the value
 * in {@link ILOAD#execute(Storage)}
 * 
 * @param variable
 */
public ILOAD(final String variable)
{
    this.variable = variable;
}


/**
 * retrieve the variable value using its name from the storage and push it on the stack
 */
public void execute(Storage storage) {
    storage.getStack().push(storage.getVariables().load(variable));
}

变量类

String variable;

/**
 * Constructor for objects of class Variable
 */
public Variable(final String variable)
{
    this.variable = variable;
}

/**
 * Create a ILOAD instance and pass it the variable name. 
 * ILOAD extends Instruction and overrides the method {@link Instruction#execute(Storage)}
 * which get as argument the {@link Storage} class and from which the value can be retrieved.  
 */
public void generateCode(final Program program) {
    program.append(new ILOAD(variable));
}
于 2014-05-10T11:42:37.913 回答