如何在不使用循环或任何java内置方法的情况下找到3字短语中第二个单词的长度



我想知道如何在不使用for或while循环以及任何内置的java方法(如substring、match、left或right。。。等等。这必须使用indexOf((来完成;方法和字符。样本输入:灰色大象---->样本输出:第二个字母有4个单词

我使用for循环完成了这项任务,但我们的老师限制了它,我想知道的是,有没有任何方法可以分解for循环,这意味着保持一切不变,但删除循环,然后手动执行。我不想要任何其他解决方案,如果你能修复我的代码,因为过程是正确的,它可以与for循环一起工作。但如果没有它,我需要它,我想如果声明可以的话,但我不知道该把它们放在哪里。

或者,如果不起作用,那么我认为它涉及indexOf((的重载版本;方法我该如何使用它?

代码:

else if (option == 2){
int first = -1;
int last = -1;
for (int x = 0; x < phrase.length() && x > phrase.indexOf(x); x++){ 
char n = phrase.charAt(x);
if (n == ' ' && first == -1){ 
first = x;
}
else if (n == ' '){ 
last = x;
}
}
int length = last - first - 1; 
System.out.print("Second word has "+length+" letters");
}   

按如下操作:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int index1 = phrase.indexOf(' ');
int index2 = phrase.indexOf(' ', index1 + 1);
System.out.println("Length of the second word is " + (index2 - index1 - 1));
}
}
}

样本运行:

Enter option: 2
Enter phrase: The grey elephant 
Length of the second word is 4

另一个样本运行:

Enter option: 2
Enter phrase: Good morning world!
Length of the second word is 7

[更新]

根据OP的请求发布以下更新,以查找第一个单词和最后一个单词的长度。

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int firstIndex = phrase.indexOf(' ');
System.out.println("Length of the first word is " + firstIndex);
System.out.println("Length of the last word is " + (phrase.length() - phrase.lastIndexOf(' ') - 1));
}
}
}

样本运行:

Enter option: 2
Enter phrase: Good morning world
Length of the first word is 4
Length of the last word is 5

这里是如何计算第二个单词的长度(假设字符串的分隔符只有一个空格。

String str = "The grey elephant";
int start = str.indexOf(' ');
int end = str.indexOf(' ', start+1);
int lengthSecondWord = end - start - 1;
System.out.println("2nd word length " + lengthSecondWord);

相关内容

最新更新