如何从同一个java项目中的不同类调用另一个方法

时间:2013-11-05 16:42:19

标签: java methods

如何从java项目中的其他类调用方法?我有两个不同的类,每个类都在同一个java项目中。第一个类的名称是Applications,而ShowChar中的第二个类的名称。这些类都在同一个java项目中。我必须做的是从用户获取字符串输入,然后我必须从用户获得一个整数,然后我必须告诉用户他们选择的整数上有什么字母。我做了所有这些。这就是ShowChar类所做的,但我应该做的是从Applications类中的ShowChar类调用一个方法。我不能让这个工作。请帮忙。

这是我的ShowChar课程 -

public class ShowChar {


char showChar(String text, int index)
{
    char letter='0';

    if((text.equals(null)))
    {
    System.out.print("Invalid input string. The process"
                          + "terminates");
    }
    else{ 
        if(index<0 || index>=text.length())
        {
            System.out.print("Invalid input for index\n"
                           + "The first character of the text is " + text.charAt(0));
            return letter;
        }
    else{
        if(index>=0 && index<text.length()) 
        {
        System.out.println("The character you asked for is: " + text.charAt(index));
        return letter;
        }
    }
    }

return letter;
}
}`     

这是我用我的应用程序类弄清楚的东西 -

public static void main(String[] args) {
    Scanner keyboard= new Scanner(System.in);




    String text=JOptionPane.showInputDialog("Enter the text: ");
    System.out.println("Enter the index: ");
    int index= keyboard.nextInt();

    ShowChar sc = new ShowChar();




    System.out.println("character found: " + sc.showChar(text, index) );



}

}

在底部,我应该在控制台上打印我找到的信,但我似乎无法让它工作。每当我使用任何输入运行我的程序时,System.out.println语句总是返回“找到的字符:0”我必须遗漏一些东西。

2 个答案:

答案 0 :(得分:2)

您没有为信件

指定值
char showChar(String text, int index)
{
    char letter='0';

    if((text.equals(null)))
    {
    System.out.print("Invalid input string. The process"
                          + "terminates");
    }
    else{ 
        if(index<0 || index>=text.length())
        {
            System.out.print("Invalid input for index\n"
                           + "The first character of the text is " + text.charAt(0));
            return letter;
        }
    else{
        if(index>=0 && index<text.length()) 
        {
        System.out.println("The character you asked for is: " + text.charAt(index));
        letter = text.charAt(index);
        return letter;
        }
    }
    }

return letter;
}

答案 1 :(得分:0)

将初始化设为:

char letter='0';

但是你以后永远不会给char赋值,这就是为什么它返回&#34; 0&#34;这是默认值。

建议:

if(index>=0 && index<text.length()) 
        {
        System.out.println("The character you asked for is: " + text.charAt(index));
        letter = text.charAt(index));
        return letter;
        }
相关问题