Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我需要帮助制作一个java构造函数,该构造函数生成一个字符串并使用适当的in初始化值var_Java_String_Constructor - Fatal编程技术网

我需要帮助制作一个java构造函数,该构造函数生成一个字符串并使用适当的in初始化值var

我需要帮助制作一个java构造函数,该构造函数生成一个字符串并使用适当的in初始化值var,java,string,constructor,Java,String,Constructor,很抱歉,如果我的问题是愚蠢的,但我已经两年没有做过java了。我现在在我的硬件中工作,我离完成还有一个方法。但是我的一个构造器是错误的,idk在哪里。提前谢谢! 值变量是一个私有整数。 到目前为止,我已经: public FancyInt(String a) { value = ""; a = this.value; } 基本上,此构造函数接受一个字符串并将值初始化为适当的int如果您说变量“value”是整数,那么您的代码无法编译,因为您正在将字符串(在本例中

很抱歉,如果我的问题是愚蠢的,但我已经两年没有做过java了。我现在在我的硬件中工作,我离完成还有一个方法。但是我的一个构造器是错误的,idk在哪里。提前谢谢! 值变量是一个私有整数。 到目前为止,我已经:

public  FancyInt(String a) {
       value = "";

       a = this.value;
}

基本上,此构造函数接受一个字符串并将值初始化为适当的int

如果您说变量“value”是整数,那么您的代码无法编译,因为您正在将字符串(在本例中为空字符串“”)赋给整数

根据您的最后一句话,我认为您的代码应该如下所示:

public FancyInt(String a) {

     this.value = isInteger(a)? Integer.parseInt(a) : 0;
}

private boolean isInteger(String val) {

    try{
        Integer.parseInt(val);
        return true;
    } 
    catch (NumberFormatException e) {
        return false;
    }
}

您可以更改isInteger方法的实现,在此链接中,您有多个选项可以帮助您。

首先,如果您想将“value”等于“a”,您必须写:

this.value = a;
在Java(以及许多编程语言)中,您必须在等分之前编写更改的变量

第二,如果将“值”设为整数。必须先将其更改为int:

try {
   this.value = Integer.parseInt(a);
} catch (NumberFormatException e) {
    e.printStackTrace();
}
第三,如果“value”是整数。您必须用数字来定义:

value = ""; //if value is an Integer, delete this line.

在这里,您试图将a分配给对象变量,这是错误的,您执行以下操作,而不是
this.value=a
But,
Integer.parseInt(val)不会返回布尔值。是的,我犯了一个错误。修好了。