简体   繁体   English

如何打印一行中第 N 个单词的第 N 个字符?

[英]How do I print the Nth character of the Nth word in a line?

I am working on a homework problem which requests that print the Nth character the Nth word on the same line with no spaces.我正在处理一个作业问题,该问题要求在同一行上打印第 N 个字符和第 N 个单词,并且没有空格。 If the Nth word is too short and does not have Nth character, the program shall print the last character of that word.如果第 N 个单词太短并且没有第 N 个字符,程序将打印该单词的最后一个字符。 If the user enters an empty word (simple presses), that words shall be disregarded.如果用户输入一个空词(简单的按下),该词将被忽略。

(We haven't learned methods yet so I am not supposed to use them) (我们还没有学习方法,所以我不应该使用它们)

See the code below, I am not sure how to get my code to print the last character of that word if it does not have the Nth character.请参阅下面的代码,如果它没有第 N 个字符,我不确定如何让我的代码打印该单词的最后一个字符。

import java.util.Scanner;

public class Words {

    public static void main(String[] args) {
        final int N=5;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a line of words seperated by spaces ");
        String userInput = input.nextLine();
        String[] words = userInput.split(" ");
        String nthWord = words[N];

        for(int i = 0; i < nthWord.length();i++) {
            if(nthWord.length()>=N) {
                char nthChar = nthWord.charAt(N);
                System.out.print("The " + N + "th word in the line entered is " + nthWord + "The " + N + "th charecter in the word is " + nthChar);
            }
            if(nthWord.length()<N) {
                    char nthChar2 = nthWord.charAt(nthWord.length()-1);
                    System.out.print("The " + N + "th word in the line entered is " + nthWord + "The " + N + "th charecter in the word is " + nthChar2);
        }
        input.close();
    }

}
}

When I run this I get an error:当我运行它时,我得到一个错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
    at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
    at java.base/java.lang.String.charAt(String.java:702)
    at Words.main(Words.java:24)

I expect to see the Nth word and the Nth character on the same line我希望在同一行上看到第 N 个单词和第 N 个字符

User input can also contain less than N words, right?用户输入也可以包含少于 N 个单词,对吧? First check should be that.首先检查应该是那个。

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a line of words seperated by spaces ");
    String userInput = input.nextLine();
    String[] words = userInput.split(" ");
    int n = words.length();
    System.out.print("Enter lookup word - N");
    int askedFor = input.nextInt();
    if (askedFor > n) {
        //your logic for this condition
        return;
    }
    String nthWord = words[askedFor-1];
    if (nthWord.length() < askedFor) print(nthWord.charAt(nthWord.length()-1));
    else print(nthWord.charAt(askedFor-1));
    input.close();
}
//Considering line as your input
String[] words = line.split(" ");

//Check if Nth word exists
if(words.length < N){
 System.out.println("Nth word does not exists");
 return;
}

//Check if Nth character exists in Nth word
if(words[N-1].length() < N){
 System.out.println("Nth character in Nth word does not exists");
 return;
}

// returning Nth character from Nth word
// Here N-1 = N; as programming starts with 0th index
return words[N-1].charAt(N-1);

Streams in Java could be a bit harder but, why not?! Streams中的流可能有点难,但是,为什么不呢?!

You can define a generic function working for any sequence:您可以定义适用于任何序列的通用 function:

static <T> T nthOrLastOrDefault(Collection<T> xs, int nth, T defaultValue) {
    return xs.stream()                                      // sequence as stream
            .skip(nth - 1)                                  // skip n - 1
            .findFirst()                                    // get next (the nth)
            .orElse(xs.stream()                             // or if not available
                    .reduce(defaultValue, (a, b) -> b));    // replace defaultValue with the next and so on
}

Returning the nth element, if not the last one, if not the default value.返回第 n 个元素,如果不是最后一个,如果不是默认值。

Now you simply apply that function for all words and then for the returned word.现在您只需将 function 应用于所有单词,然后应用于返回的单词。

(Unfortunately Java manages characters differently and must be converted from integers to characters) (很遗憾Java对字符的管理方式不同,必须从整数转换为字符)

String nthWord = nthOrLastOrDefault(asList(words), N, "");

List<Character> chars = nthWord.chars().mapToObj(i -> (char) i).collect(toList()); // ugly conversion

char nthNth = nthOrLastOrDefault(chars, N, '?');

The output could be output 可以是

Enter a line of words seperated by spaces:
one two three four five six
The nth char or last or default of the nth word or last or default is 'e'
Enter a line of words seperated by spaces:
one two three four
The nth char or last or default of the nth word or last or default is 'r'
Enter a line of words seperated by spaces:

The nth char or last or default of the nth word or last or default is '?'
Enter a line of words seperated by spaces:

(Complete example code) (完整的示例代码)

static <T> T nthOrLastOrDefault(Collection<T> xs, int nth, T defaultValue) {
    return xs.stream()                                      // sequence as stream
            .skip(nth - 1)                                  // skip n - 1
            .findFirst()                                    // get next (the nth)
            .orElse(xs.stream()                             // or if not available
                    .reduce(defaultValue, (a, b) -> b));    // replace defaultValue with the next and so on
}

public static void main(String[] args) {
    final int N = 5;
    try (final Scanner input = new Scanner(System.in)) {
        while (true) {
            System.out.println("Enter a line of words seperated by spaces:");

            final String userInput = input.nextLine();

            final String[] words = userInput.split(" ");

            String nthWord = nthOrLastOrDefault(asList(words), N, "");

            List<Character> chars = nthWord.chars().mapToObj(i -> (char) i).collect(toList()); // ugly conversion

            char nthNth = nthOrLastOrDefault(chars, N, '?');

            System.out.printf("The nth char or last or default of the nth word or last or default is '%c'%n", nthNth);
        }
    }
}

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

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