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

Java代码运行后类属性仍为初始值,请求排查问题原因

问题分析:输入产品信息后输出初始值的原因

核心错误点:

  • 局部变量覆盖成员变量:在read()方法中,重新声明了与类成员变量同名的局部变量(String name、double price),导致代码仅给局部变量赋值,完全没修改Product类的成员属性。正确做法是去掉变量类型声明,直接给成员变量赋值。
  • 变量名拼写错误:read()方法里把类成员变量score写成了core,导致类的score属性始终是构造方法中的初始值0。
  • 重复创建Scanner对象:read()方法内新建了Scanner实例,而main方法已有一个Scanner,重复创建可能引发输入异常,建议复用同一个Scanner。

修正后的代码:

import java.util.Scanner;

class Product{
    
    //Class attributes
    private String name;
    private double price;
    private int score; 
    
    public Product() {
        name = "";
        score = 0; 
        price = 1;
    }
    
    public void printData(){
        System.out.println("Name: " + name);
        System.out.println("Price: " + price);
        System.out.println("Score: " + score);
    }
    
    // 接收外部传入的Scanner,避免重复创建
    public void read(Scanner in) {
        System.out.println("Product name: ");
        name = in.nextLine(); // 直接给成员变量赋值,不声明局部变量
        System.out.println("Price: ");
        price = in.nextDouble(); // 同上
        System.out.println("Score: ");
        score = in.nextInt(); // 修正拼写错误,给score赋值
        in.nextLine(); // 读取nextInt后的换行符,避免后续输入异常
    }
    
    public boolean is_better_than(Product other) {
        // 整数除法转成double计算,避免精度丢失
        return (double)score / price > (double)other.score / other.price;
    }
}


public class Main {
    public static void main(String[] args) {
 
        Scanner in  = new Scanner(System.in);
        
        Product best = new Product();
        
        boolean more = true;
        while(more) {
            Product current = new Product();
            current.read(in); // 传入已有的Scanner
            if (current.is_better_than(best)) {
                best = current;
            }
                            
            System.out.println("More Products? 1:YES, 2:NO");
            int answer  = in.nextInt();
            if (answer != 1)
                more = false;
            in.nextLine(); // 清除换行符
        
        }
        
        best.printData(); 
    }
}

额外优化说明:

  • is_better_than方法中,将整数除法转为double类型计算,避免因整数除法丢失精度导致比较逻辑错误。
  • read方法中添加in.nextLine()处理nextInt后的换行符,防止后续输入产品名称时直接读取空字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 12:01:20