简体   繁体   English

Java中的单词计数器程序

[英]Word counter Program In Java

While creating a word counter in java through collecting user input from a scanner I've been running into the error of having my program display that there was one extra word entered when there is a space entered in after the final word in the char. 在Java中通过收集来自扫描仪的用户输入来创建字计数器时,我遇到了一个错误,即我的程序显示在char中的最后一个单词之后输入空格时输入了一个额外的单词。 Is there a way to check the user input for a space and remove it before entering my word count loop? 有没有一种方法可以检查用户输入的空格并在进入我的单词计数循环之前将其删除?

Right after... 之后...

String userinput = wordcounter.nextLine();

... add this line: ...添加以下行:

userinput = userinput.trim();

It should fix the problem, since the function trim() gets rid of any blank spaces at the beginning or ending of the string. 它应该解决问题,因为函数trim()消除了字符串开头或结尾的任何空格。

Try something like this: 尝试这样的事情:

public static void main(String[] args) {
    int word = 0;
    System.out.println("Enter a string: ");
    Scanner wordcounter = new Scanner(System.in);
    while (wordcounter.hasNext()) {
        wordcounter.next();
        word++;
    }
    System.out.println("You hav entered " + word + " words.");
}

Moreover there are many functions in Java that you can use here to do this very easily like using string tokenizer, etc. But if you want to make changes in the above program, you could simply do a simple check statement before the main if condition that if the I == length-1, because this means that you are at the last character and there is nothing after this, for this case you could just continue or break. 而且,Java中有许多函数可以很容易地在其中使用,例如使用字符串标记程序等。但是,如果要在上述程序中进行更改,则可以简单地在main if条件之前做一个简单的check语句。如果I == length-1,因为这意味着您位于最后一个字符,并且此后没有任何内容,在这种情况下,您可以继续或中断。 Hopefully I solved your query, do tell in case you need more clarification... 希望我能解决您的查询,如果需要进一步说明,请告诉我...

One possible way: use regex after you trim your input. 一种可能的方式: 修剪输入后使用正则表达式。


String text = "I turned myself into a pickle Morty! :)";
String[] words = text.split("([\\W\\s]+)");
int count = 0;
for (String word: words) {
    count++;
}
System.out.println("You have entered " + count + " words!");
    Scanner in = new Scanner (System.in);
    System.out.println("Write something");
    String x = in.nextLine();
    char y;
    char z;
    int n =1;
    boolean t = true;
    boolean f = false;
    boolean o = false;
    for (int i = 0; i<x.length();i++){
    y = x.charAt(i);
    if(t){
    if(' ' == y){n--;}
    else if(y != ' '){ t=false; f = true;}
    }
    if(' ' == y){n++;}
    if(o){
        z = x.charAt(i-1);
    if(' ' == y && ' '== z){n--;}
    }
    if (o){
    if(' ' == y && i == x.length()-1){n--;}
    }
    if(f){o = true;}

    }
    System.out.println(n);

This actually works lol 这实际上有效

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

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