【问题标题】:What's wrong with my showChar method? Simple program intro to methods我的 showChar 方法有什么问题?方法的简单程序介绍
【发布时间】:2015-11-06 19:36:10
【问题描述】:

//Ch5a 程序

'我应该使用一种方法来显示用户输入的单词的某个字母。

我需要使用 showChar。 我看不到任何明显的错误,我已经研究了几个小时。'

import javax.swing.JOptionPane;
public class Ch5a {
    public static void main(String[] args){
        String inputString = JOptionPane.showInputDialog("What word would you like to analyze?");
        String inputNumberString = JOptionPane.showInputDialog("What letter would you like to see? (Eg: For the second letter of 'dog', input 2)");
        int inputNo;
        inputNo = Integer.parseInt(inputNumberString);
    /**
     At this point, i have an input number from the user(inputNo) and I have a word from the user(inputString).
     I then print the inputNo for testing.
     */
        System.out.println(inputNo);
    //time to call the method.
        char answer;
    //I declare the character answer.
        answer = showChar(inputString, inputNo);
    //i set it equal to the result of the method.
        System.out.println("The " + inputString +" number character in " + inputNo + " is" + answer);

}
    public static char showChar(String inputString, int inputNo){
     //local variable
        char result;
        result = showChar(inputString, inputNo); //user's chosen character
    //returning whatever i want in place of the method call(in this case, "result")
        return result;
    }
}

【问题讨论】:

  • 不清楚你的 showChar 方法应该做什么,但它可能不应该调用自己。

标签: java methods char


【解决方案1】:

我想你想要这样的东西:

public static char showChar(String inputString, int inputNo){
    char result;
    result = inputString.charAt(inputNo -1);   // since index starts at 0
    return result;
}

【讨论】:

    【解决方案2】:

    看看String.charAt() 方法。我想你想要的更像是:

        public static char showChar(String inputString, int inputNo){
    
           char result;
    
           result = inputString.charAt(inputNo - 1); 
    
           return result;
        }
    

    或简化:

        public static char showChar(String inputString, int inputNo){
           return inputString.charAt(inputNo - 1); 
        }
    

    查看http://www.tutorialspoint.com/java/java_string_charat.htm了解更多信息

    【讨论】:

    • 应该输入No - 1,正如@Kevin Mee所说的
    【解决方案3】:
     public static char showChar(String inputString, int inputNo){
        inputNo = inputNo-1; // first letter in String has position 0
        if(inputNo<0 || inputNo>=inputString.length())
        {
            // if the number is out of Bounds
            return ' ';
        }
    return inputString.charAt(inputNo);
    }
    

    【讨论】:

    • 哦,这很有趣。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    相关资源
    最近更新 更多