0

我目前正在使用 StringTokennizer 类将字符串拆分为不同的标记,如定义的分隔符..

public class App {  
    public static void main(String[] args) {  

        String str = "This is String , split by StringTokenizer, created by Neera";  
        StringTokenizer st = new StringTokenizer(str);  


        System.out.println("---- Split by comma ',' ------");  
        StringTokenizer st2 = new StringTokenizer(str, ",");  

        while (st2.hasMoreElements()) {  
            System.out.println(st2.nextElement());  
        }  
    }  
}  

我的疑问是,同样的事情也可以通过扫描仪类来实现......!!自从我阅读以来,使用扫描仪类是否正确? t工作...请告诉我..!!!

public class App1 {  

    public static void main(String[] args)    
    {  
        Scanner scanner =  new Scanner("This is String , split by StringTokenizer, created by Neera").useDelimiter(", ");    

        while (scanner.hasNextLine()) { 
            System.out.println(scanner.nextLine());
        }
    }
}
4

1 回答 1

0

用于scanner.next()返回下一个标记scanner.nextLine(),而不是返回下一个完整行(并且您的输入只有一个)。当然,你会想hasNext()在你的while而不是hasNextLine().

回应您的评论:

您的代码有语法错误,我最初认为这是一个错字并在问题中更正。你在写:

while (scanner.hasNext()) ;
    System.out.println(scanner.next());

哪个格式正确应该告诉你真正发生了什么:

while (scanner.hasNext())
    ; // empty statement
System.out.println(scanner.next());

它应该是:

while (scanner.hasNext()) {
    System.out.println(scanner.next());
}
于 2012-04-08T05:12:23.820 回答