[英]StringTokenizer: 'NoSuchElementException' and a few other problems
In this program, I have a String with words separated by spaces and I want to remove a particular word and then print the new String.在这个程序中,我有一个用空格分隔单词的字符串,我想删除一个特定的单词,然后打印新的字符串。 This is my code below:
这是我的代码如下:
import java.util.*;
class A
{
public static void main()
{
String str="Monday Tuesday Wednesday";
String newstr="";
StringTokenizer S=new StringTokenizer(str);
while(S.hasMoreTokens()==true)
{
if(S.nextToken().equals("Tuesday"))
{
continue;
}
else
newstr=newstr+(S.nextToken()+" ");
}
System.out.println(newstr);
}
}
In the above code, I want to delete the word 'Tuesday' from the String, and print the new String.在上面的代码中,我想从字符串中删除“星期二”这个词,并打印新的字符串。 But when I run the program, the following exception is thrown:
但是当我运行程序时,抛出了以下异常:
When I want to remove the word 'Wednesday' after changing the code, only 'Tuesday' is shown on Output screen.当我想在更改代码后删除“星期三”这个词时,输出屏幕上只显示“星期二”。 Likewise, when I want to remove 'Monday', only 'Wednesday' is shown as output.
同样,当我想删除“星期一”时,只显示“星期三”作为输出。
I would really like some help on this so that I that I can understand the 'StringTokenizer' class better.我真的很想在这方面提供一些帮助,以便我可以更好地理解“StringTokenizer”类。
Thank You!谢谢你!
StringTokenizer.nextToken()
increments the token upon each call. StringTokenizer.nextToken()
在每次调用时增加令牌。 You should only call it once per loop, and save the value it returns in the local scope.每个循环只应调用一次,并将它返回的值保存在本地作用域中。
import java.util.StringTokenizer;
class A {
public static void main(String[] args) {
String str = "Monday Tuesday Wednesday";
String newstr = "";
StringTokenizer S = new StringTokenizer(str);
while(S.hasMoreTokens() == true) {
String day = S.nextToken();
if(day.equals("Tuesday")) {
continue;
} else {
newstr = newstr + (day + " ");
}
}
System.out.println(newstr);
}
}
returns Monday Wednesday
Monday Wednesday
返回
public class A {
public static void main(String[] a) {
String str = "Monday Tuesday Wednesday";
String newstr = "";
StringTokenizer S = new StringTokenizer(str," ");
while (S.hasMoreTokens()) {
String token = S.nextToken();
if (token.equals("Tuesday")) {
continue;
} else
newstr = newstr + (token + " ");
}
System.out.println(newstr);
}
}
you have to take nextToken only once你只需要拿 nextToken 一次
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.