Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 关于索引_Java_Indexof_Spaces - Fatal编程技术网

Java 关于索引

Java 关于索引,java,indexof,spaces,Java,Indexof,Spaces,当用户输入0时,它打印第一个,或者当用户输入1时,它打印第二个 因此,我决定如何创建它的方法是找到两个空格的索引,其中包括特定字符串:“1st”或“2nd”或“3rd”…,并将这些索引分配到两个变量中,称为start和end。并将两者作为子字符串的参数来打印特定字符串 在上面的代码中,它一直工作到变量x为6,以下是输出: String str = "1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th"; 它重复15次,字符串不应该是第6个,应该是: 0:1, 1:

当用户输入0时,它打印第一个,或者当用户输入1时,它打印第二个

因此,我决定如何创建它的方法是找到两个空格的索引,其中包括特定字符串:“
1st”或“2nd”或“3rd”…
,并将这些索引分配到两个变量中,称为start和end。并将两者作为子字符串的参数来打印特定字符串

在上面的代码中,它一直工作到变量x为6,以下是输出:

String str = "1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th";
它重复15次,字符串不应该是第6个,应该是:

0:1, 1:2, 2:3, 3:4, 4:5, 5:6, 6:7 等等

而且不仅是6,当变量x是10时,它还会重复一个数字27两次

我试图找到问题,但我不知道

有人知道问题出在哪里吗?如何修复它


谢谢

代码中有几点需要注意,但主要是,您的错误归结为以下几行:

current start: 0
current start: 3
current start: 7
current start: 11
current start: 15
current start: 15
HERE:  6th
…再加上令人费解的:

start = str.indexOf(" ", temp3); // why temp3?
相反,只需删除
temp3
变量,然后执行
indexOf
如下操作:

temp3 += str.indexOf(" "); // no idea what this is trying to do.

您的解决方案存在一些问题。字符串不以空格结尾,因此如果尝试在

start = str.indexOf(" ", start + 1); // start + 1: look right after the last space that was found.
对于最后一个元素,您将得到-1

同样,当您在循环中时,您希望temp3指向下一个空间位置,但您将temp指定为

end = str.indexOf(" ", start + 1);
这将始终在temp3中添加3个字符,但当元素数量增加时,字符数量并不总是3个,例如“10”需要4个字符,因此不能只在temp3中添加3个字符

我想你需要的是

temp3 += str.indexOf(" ");
你很快就会意识到你根本不需要temp3

一个更简单的解决方案是按空格分割字符串,然后像这样返回第x个元素

temp3 = start+1

你应该看看这个方法是的,split在我的程序中工作得很好,谢谢:)永远不知道有split,是的,它正是我想要的,谢谢:)没问题,java有很多免费内置的功能!
temp3 = start+1
    String str = "1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th";

    int x = 6;

    String[] tokens = str.split(" ");

    System.out.println(tokens[x]);