将数组中字符串的值传递给java中的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19965895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:53:09  来源:igfitidea点击:

Passing value of a string in an array to a method in java?

javaarraysstring

提问by user2333867

thank you for taking the time to read this. Sorry if my question is dumb, I tried searching but couldn't quite figure out why I'm having this problem. I was trying to test some code for another application, but I'm having issues. Perhaps I just don't understand arrays properly.

感谢您抽出时间来阅读。对不起,如果我的问题很愚蠢,我尝试搜索但无法弄清楚为什么我会遇到这个问题。我试图为另一个应用程序测试一些代码,但我遇到了问题。也许我只是没有正确理解数组。

I have a method named halfStepUp in a class named Transpose that, for testing purposes, should return "c#" if given "c" and "d#" if given "d". This is the code:

我在名为 Transpose 的类中有一个名为 halfStepUp 的方法,出于测试目的,如果给定“c”,则应返回“c#”,如果给定“d”,则应返回“d#”。这是代码:

public class Transpose{
    public static String halfStepUp(String note){
        String n = null;
        if (note == "c") n = "c#";
        if (note == "d") n = "d"#;
        return n;
    }   
}

I have the following code in my main method:

我的主要方法中有以下代码:

String [] scale = new String[2];
scale[0] = "c";
scale[1] = "d";

System.out.println(Transpose.halfStepUp(scale[0]));

This prints "null." What am I doing wrong? I know the method works because if I use

这将打印“null”。我究竟做错了什么?我知道该方法有效,因为如果我使用

System.out.println(Transpose.halfStepUp("c"));

It works fine. The solution is probably embarrassingly easy but I couldn't find a good way to word it when searching for help. Thanks again for reading, and any answers are greatly appreciated!

它工作正常。解决方案可能非常简单,但在寻求帮助时我找不到一个好的表达方式。再次感谢您的阅读,非常感谢您的回答!

采纳答案by Sterling Archer

Try this instead: (edited from comments)

试试这个:(从评论中编辑)

public class Transpose{
    public static String halfStepUp(String note){
        String n = null;
        if ("c".equals(note)) n = "c#"; //using .equals as a string comparison
        if ("d".equals(note)) n = "d#"; //not "d"#
        return n;
    }   
}

回答by Andrey Chaschev

The glitch is in this line:

故障在这一行:

 if (note == "c") n = "c#";

This compares strings by address, not by value. Try using "c".equals(note)instead.

这按地址比较字符串,而不是按值。尝试使用"c".equals(note)

回答by matt forsythe

You should use the .equals()method when comparing strings, not ==. The ==operator compares the references to see if they are pointing to the same underlying object. The .equals()method, compares the underlying objects to each other to see if they are semantically equivalent.

您应该.equals()在比较字符串时使用该方法,而不是==. 该==运营商比较引用,看看他们都指向同一个底层对象。该.equals()方法将底层对象相互比较,以查看它们在语义上是否等效。

回答by Mamed Khazri

class Transpose{
    public static String halfStepUp(String note){
        String n = null;
        if (note == "c") n = "c#";
        if (note == "d") n = "d#";
        return n;
    }
}
public class TransposeTest {
    public static void main(String... args) {
        String [] scale = new String[2];
        scale[0] = "c";
        scale[1] = "d";
        System.out.println(Transpose.halfStepUp(scale[0]));
    }
}

working code

工作代码

回答by Johannes H.

To add a little more info to the answers you already got:

要为您已经得到的答案添加更多信息:

Java has two types of storage. One is the stack, which includes variable names and their values. One is the heap, that is just a huge collections of free-floating objects.

Java 有两种类型的存储。一种是堆栈,其中包括变量名称及其值。一个是堆,它只是一个巨大的自由浮动对象集合。

Now, if you're working with primitive types (like int, booleanor char), assigning a variable like
int myInt = 1;
pushes that variable on thje stack - the name is myInt, the value is 1.

现在,如果您正在使用原始类型(如 intbooleanchar),则分配一个变量,例如
int myInt = 1;
将该变量推入堆栈 - 名称为myInt,值为1

If you, however, have an object (like strings are), assigning a variable does a little bit more.
String myString = "Hey!";
now creates an object (instance of String) somewhere on the heap. It has no name there, only some address in the memory where it can be found.
In addition to that, it pushes a variable on the stack. The name is myString- and the value is the address of the object on the heap.

但是,如果您有一个对象(如字符串),则分配一个变量会做更多的工作。
String myString = "Hey!";
现在String在堆的某处创建一个对象(实例)。它在那里没有名字,只有内存中可以找到它的某个地址。
除此之外,它还将一个变量压入堆栈。名称是myString-,值是堆上对象的地址。

So why is this relevant to comparing variables? Because ==compares values of variables. ON THE STACK, that is. SO if you compare primitive types, everything works as expected. But if you're comparing Objects, ==still only compares the values of the variables - which is, in that case, the addresses to the objects. If the addresses are the same, it returns true. That does mean, both variables point to the same object. If the addresses are different, ==returns false., Without ever looking at the heap, where the objects really are.

那么为什么这与比较变量有关?因为==比较变量的值。在堆栈上,就是这样。所以如果你比较原始类型,一切都按预期工作。但是如果你比较对象,==仍然只比较变量的值——在这种情况下,也就是对象的地址。如果地址相同,则返回 true。这确实意味着,两个变量都指向同一个对象。如果地址不同,则==返回 false。,无需查看堆,即对象真正所在的位置。

An example:

一个例子:

String a = new String("Hey!");
String b = a;
if (a == b) System.out.println("true");
else System.out.println("false");

will echo "true" - because both variables contain the same object.

将 echo "true" - 因为两个变量都包含相同的对象。

String a = new String("Hey!");
String b = new String("Hey!");
if (a == b) System.out.println("true");
else System.out.println("false");

will echo "false" - because you have two objects on the heap now, and apoints to the one, while bpoints to the other. So while the contents of both objects may be the same, the contents of aand bon the stack are different.

将回显“false” - 因为您现在在堆上有两个对象,并且a指向一个,而b指向另一个。因此,虽然两个对象的内容可能相同,但堆栈中的a和的内容b是不同的。

Therefore, to compare any object, always use .equals()if you want to compare contents, not instance-equality.

因此,要比较任何对象,.equals()如果要比较内容,请始终使用,而不是实例相等。

[Addendum]: With strings, this is even more complicated. As you already found out already,

[附录]:对于字符串,这更加复杂。正如你已经发现的那样,

String a = "Hey!"; // mention the difference to the example above:
String b = "Hey!"; // I did NOT use the `String()` cosntructor here!
if (a == b) System.out.println("true");
else System.out.println("false");

will actually give you "true". Now why is THAT? One might think that we still create two objects. But actually, we are not.

实际上会给你“真实”。那是为什么?有人可能认为我们仍然创建了两个对象。但实际上,我们不是。

Stringis immutable. That means, once a String has been created, it cannot be modified. Ever. Don'T believe that? Take a look!

String不可变的。这意味着,一旦创建了一个字符串,就不能对其进行修改。曾经。不相信吗?看一看!

String myString = "test"; // we create one instance of String here
myString += " and more"; // we create another instance of String (" and more")
                         // and append that. Did we modify the instance stored in
                         // myString now? NO! We created a third instance that
                         // contains "test and more".

Therefore, there is no need to create additional instances of Stringwith the same content - which increases performance, as Strings are widely used, in masses, so we want to have as few of them as possible. To archive that, the JVM maintains a list of String Objects we already created. And every time we write down a String literal (that is something like "Hey!"), it looks in that lists and checks if we already created an instance that has that value. If so, it returns a pointer to that exact same instance instead of creating a new one.

因此,无需创建String具有相同内容的额外实例- 这会提高性能,因为字符串被广泛使用,大量使用,因此我们希望尽可能少地使用它们。为了存档,JVM 维护了一个我们已经创建的字符串对象列表。每次我们写下一个字符串文字(类似于"Hey!")时,它都会查看该列表并检查我们是否已经创建了一个具有该值的实例。如果是这样,它会返回一个指向该完全相同实例的指针,而不是创建一个新实例。

And THIS is, why "Hey!" == "Hey!"will return true.

这就是,为什么"Hey!" == "Hey!"会返回 true。