Java 如何将字符值从一种方法返回到另一种方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21843270/
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-13 11:01:29  来源:igfitidea点击:

How to return a char value from one method to another?

java

提问by user3321212

This is what I have...

这就是我所拥有的...

{
   public static void main(String[] args)
   {
      //variable declaration
      char letter;

      getLetter();

      letter = "";
      System.out.println(letter)
   }

   public static int getLetter()
   {
      String text;
      char letter;

      text = JOptionPane.showInputDialog("Enter a letter.");
      letter = text.charAt(0);

      System.out.println(letter);

      return letter;
   }
}

I want to get the letter the user inputs from the method getLetter and transfer it in the main method where I can display it on the screen. What am I doing wrong here?

我想从 getLetter 方法中获取用户输入的字母,并将其传输到 main 方法中,以便我可以在屏幕上显示它。我在这里做错了什么?

采纳答案by Rhys

The getLetter()method should return type charnot int. This is because you have assigned the local variable letteras type char.

getLetter()方法应该返回类型charnot int。这是因为您已将局部变量分配letter为 type char

Also, methods are called by method();not '(method)'.

此外,方法由method();not调用'(method)'

Try out the following code:

试试下面的代码:

public class YourClass {
  public static void main(String[] args) {
    //variable declaration
    char letter;
    letter = getLetter();
    System.out.println(letter);
  }

  public static char getLetter() {
    String text;
    char letter;

    text = JOptionPane.showInputDialog("Enter a letter.");
    letter = text.charAt(0);

  System.out.println(letter);
  return letter;
  }
}

回答by Terry Chern

The return type for your method is an int, but you're returning a character. Your method invocation is incorrect as well; it should be:

您的方法的返回类型是 int,但您返回的是一个字符。您的方法调用也不正确;它应该是:

 letter = getLetter(); // follows the same format as the declaration.

You should make use of the Java Tutorials, they can be found here: http://docs.oracle.com/javase/tutorial/

您应该使用 Java 教程,它们可以在这里找到:http: //docs.oracle.com/javase/tutorial/