You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用对象字段用于方法时遇报错:shift无法解析或不是字段

问题分析与解决步骤

你的代码里有三个核心问题导致报错,逐个解决即可:

1. 构造方法赋值顺序完全颠倒

Key类的构造方法里,你把对象成员变量的值赋给了参数,而非将参数值赋给成员变量,这会导致创建Key对象时,shift字段始终是默认值0,完全达不到初始化目的。

修正后的Key构造方法:

public Key(int ID, int shift) {
    this.ID = ID;
    this.shift = shift;
}

2. Encrypt方法的参数类型错误

你把参数声明为Object key1,但Object类并没有shift字段,编译器自然无法识别。必须把参数类型改为Key key1,让编译器明确这是Key类的实例。

3. 私有字段无法直接访问

Key类的shift字段用private修饰,意味着外部类不能直接通过key1.shift访问它。需要给Key类添加一个getter方法,用来获取shift的值。

最终完整的Key类代码

public class Key {
    private int ID;
    private int shift;

    public Key(int ID, int shift) {
        this.ID = ID;
        this.shift = shift;
    }

    // 添加getter方法
    public int getShift() {
        return shift;
    }
}

修正后的Encrypt方法

public String Encrypt(String message, Key key1) {         
    String encrypted = "";
    Scanner scn = new Scanner(message);
    while (scn.hasNextLine()){   
        String line = scn.nextLine();
        String sEncrypted = "";
        for(int i = 0; i < line.length(); i++) {
            // 通过getter方法获取shift值
            sEncrypted += (char)(line.charAt(i) + key1.getShift());
        }
        encrypted += sEncrypted;
    }
    scn.close();
    return encrypted;
}

另外补充两个小问题:原Encrypt方法没有返回加密后的字符串,且每行加密结果未拼接到最终字符串里,上面的代码已一并修正。

内容的提问来源于stack exchange,提问作者Mitchell Barrett

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 03:23:01