【问题标题】:How to find the nth letter of the phrase, and keep all the starting letters?如何找到短语的第 n 个字母,并保留所有起始字母?
【发布时间】:2020-04-20 23:08:45
【问题描述】:

如何输入一个整数 (n),然后只使用 for 循环输出短语的前 n 个字符?

例如,输入为 1(选项编号),Hussain Omer(字符串名称),9(索引) 输出应该是 Hussain O(看看如何保留第一个字母,然后给出第 n 个字母)

这是我的代码:

    import java.util.Scanner;
    public class Phrases{
    public static void main (String[]args){
    Scanner keyboard = new Scanner(System.in);
        int option = Integer.parseInt(keyboard.nextLine());
        String phrase = keyboard.nextLine();
            if (option == 1){
                int x = keyboard.nextInt();
                    for (int y = 0; y < phrase.length(); y++){
                        char n = phrase.charAt(y);
                            if (y < phrase.length()-y) 
                                System.out.print(n);
                            if (y == x - 1) 
                                System.out.print(n);
                    }
            }

【问题讨论】:

    标签: java


    【解决方案1】:

    您只需要打印索引处的字符,y 其中y &lt; x。注意x &gt;= phrase.length()时还需要勾选y &lt; phrase.length(),避免StringIndexOutOfBoundsException

    按如下方式进行:

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
            int option = Integer.parseInt(keyboard.nextLine());
            String phrase = keyboard.nextLine();
            if (option == 1) {
                int x = keyboard.nextInt();
                for (int y = 0; y < x && y < phrase.length(); y++) {
                    System.out.print(phrase.charAt(y));
                }
            }
        }
    }
    

    示例运行:

    1
    Hussain Omer
    9
    Hussain O
    

    或者,您可以使用substring(int beginIndex, int endIndex)

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
            int option = Integer.parseInt(keyboard.nextLine());
            String phrase = keyboard.nextLine();
            if (option == 1) {
                int x = keyboard.nextInt();
                if (x < phrase.length())
                    System.out.println(phrase.substring(0, x));
            }
        }
    }
    

    示例运行:

    1
    Hussain Omer
    9
    Hussain O
    

    【讨论】:

    【解决方案2】:

    只需更改您的 for 循环。如果您只想输出有限数量的字符,那么只需限制 for-cycle 有那么多步骤并输出字符。

                    for (int y = 0; y < x; y++){
                        char n = phrase.charAt(y);
                        System.out.print(n);
                    }
    

    【讨论】:

    • 条件应为y &lt; x &amp;&amp; y &lt; phrase.length(),避免StringIndexOutOfBoundsExceptionx &gt;= phrase.length()
    • 我理解 y
    猜你喜欢
    • 1970-01-01
    • 2014-01-19
    • 2021-11-10
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多