将数组中字符串的值传递给java中的方法? [英] Passing value of a string in an array to a method in java?

查看:48
本文介绍了将数组中字符串的值传递给java中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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:

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]));

这会打印null".我究竟做错了什么?我知道该方法有效,因为如果我使用

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

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!

推荐答案

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

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;
    }   
}

这篇关于将数组中字符串的值传递给java中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆