繁体   English   中英

如何从Java项目中的其他类调用方法

[英]How to call a method from a different class in a java project

如何在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”,我肯定会丢失一些东西

在以下行添加cancat运算符+

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

你不是在那样做吗?

ShowChar sc = new ShowChar(); // object of ShowCar class




    System.out.println("character found: " + sc.showChar(text, index) ); // calling a method of ShowCar class

可以使用对象名和用点号( . )分隔的方法名来调用类的方法,如下所述:

objName.methodName(params);

您在sysout中正确调用了它:

sc.showChar(text, index)

您只是想将sysout中使用+符的showChar方法的输出与“找到的字符:”字符串连接起来

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

暂无
暂无

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

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