简体   繁体   English

在方法重载中将字符串作为参数传递

[英]Passing string as a parameter in method overloading

package chapter3;
class MatchClass
{
    int x=0,y=0,z=0,res=0;
    float a=0,b=0,c=0,ress=0;
    String str=null;`enter code here`
    void add(int x,int y,int z)
    {
        res=x+y+z;
        System.out.println("Addition of integers="+res);
    }

    void add(float a, float b, float c)
    {
        ress=a+b+c;
        System.out.println("Addition of float values="+ress);
    }

    void add(String...str)
    {

        System.out.println("Concatenation of string="+str); 
    }
    public static void main(String ar[])
    {
        MatchClass ob=new MatchClass();
        ob.add(10,20,30);
        ob.add(3.5F,4.5F,6.0F);
        ob.add("Mountain","sick");

    }
}

here is the code that I have written and the output I am getting for string parameter that I have passed is quite ambiguous. 这是我编写的代码,我为传递的字符串参数获得的输出是非常模糊的。 Can someone please help me with a quick fix. 有人可以帮我快速解决问题。 PS- I want to use varagrs concept for passing string values. PS-我想使用varagrs概念传递字符串值。

I think the problem you're talking about is the output you get for the string function. 我认为您正在谈论的问题是字符串函数的输出。 Something like : 就像是 :

Concatenation of string=[Ljava.lang.String;@6d06d69c

At the line 在生产线上

System.out.println("Concatenation of string="+ str);

You're printing the variable "str" but "str" is not a string, it is an array and an array is an object. 您正在打印变量“ str”,但“ str”不是字符串,它是一个数组,而数组是一个对象。 So, in order to be printed the function .toString() is called implicitly on "str". 因此,为了进行打印,函数.toString()在“ str”上被隐式调用。 The problem here is the method Object.toString() does not print the content of the array but the object's type and reference inside the memory. 这里的问题是Object.toString()方法不会打印数组的内容,而是在内存中打印对象的类型和引用。

To print the content of the array the following will work (at least JDK8 required) 要打印数组的内容,将执行以下操作(至少需要JDK8)

System.out.println("Concatenation of string="+ String.join(",",str)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM