简体   繁体   English

我的showChar方法有什么问题? 简单的程序介绍方法

[英]What's wrong with my showChar method? Simple program intro to methods

//Ch5a Program // Ch5a程序

'I'm supposed to use a method to display a certain letter of a word input by the user. “我应该使用一种方法来显示用户输入的单词的某个字母。

I need to use showChar. 我需要使用showChar。 There aren't really any obvious errors that I can see and I've worked on it for a couple hours.' 我确实看不到任何明显的错误,并且已经解决了两个小时。

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

I think you want something like this: 我想你想要这样的东西:

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

have a look at String.charAt() method. 看一下String.charAt()方法。 I think you want something more like: 我认为您想要更多类似的东西:

    public static char showChar(String inputString, int inputNo){

       char result;

       result = inputString.charAt(inputNo - 1); 

       return result;
    }

or to simplify: 或简化:

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

see http://www.tutorialspoint.com/java/java_string_charat.htm for more info 有关更多信息,请参见http://www.tutorialspoint.com/java/java_string_charat.htm

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

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

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