【问题标题】:Trying to convert integer object which is in a class to a string试图将类中的整数对象转换为字符串
【发布时间】:2021-03-28 01:19:08
【问题描述】:

我正在尝试将类中的整数对象转换为字符串。当 CreateAccount() 被打印而不向 phone_number 添加任何变量时,我希望它打印“无信息”。但通常需要 phone_number 保持整数。


public class CreateAccount {
    
    private String customer_name;
    private int phone_number;
    private int password;
   
   
    public void CreateAccount(){
        this.customer_name = "No info";
        Integer.toString(this.phone_number);
        this.phone_number = "No info";

当我尝试使用 Integer.toString() 将 phone_number 转换为字符串时,出现“字符串无法转换为 int”错误。

【问题讨论】:

  • 您确定您正在查看正确的线路吗? this.phone_number = "No info"; 更有可能导致该消息。
  • 你应该遵循 Java 命名约定:变量名和方法名应该用驼峰命名,所以没有下划线。

标签: java class tostring


【解决方案1】:

让我们使用正确的 java 语义,并且有人告诉你,你搞砸了类型

public class Account {
        
    public int phoneNumber;
    public String customerName;

    public Account(int phoneNumber) {
        this.phoneNumber = phoneNumber;
        this.customerName = phoneNumber != 0 ? String.valueOf(phoneNumber) : "No INFO";
    }

    public int getPhoneNumber() {
        return phoneNumber;
    }

    public String getCustomerName() {
        return customerName;
    }
}

【讨论】:

  • 该死的我对“this.customerName = ...”部分一无所知。作为一个初学者,我觉得我有点过头了。感谢您的回答,我暂时跳过这个问题...
  • 这是一个快捷方式 if(phoneNumber != 0){this.customerName=String.valueOf(phoneNumber);} else {this.customerName="No INFO";}
猜你喜欢
  • 1970-01-01
  • 2011-03-24
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
  • 2017-12-03
  • 1970-01-01
  • 2011-09-30
相关资源
最近更新 更多