[英]Word counter Program In Java
在Java中通過收集來自掃描儀的用戶輸入來創建字計數器時,我遇到了一個錯誤,即我的程序顯示在char中的最后一個單詞之后輸入空格時輸入了一個額外的單詞。 有沒有一種方法可以檢查用戶輸入的空格並在進入我的單詞計數循環之前將其刪除?
之后...
String userinput = wordcounter.nextLine();
...添加以下行:
userinput = userinput.trim();
它應該解決問題,因為函數trim()
消除了字符串開頭或結尾的任何空格。
嘗試這樣的事情:
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.");
}
而且,Java中有許多函數可以很容易地在其中使用,例如使用字符串標記程序等。但是,如果要在上述程序中進行更改,則可以簡單地在main if條件之前做一個簡單的check語句。如果I == length-1,因為這意味着您位於最后一個字符,並且此后沒有任何內容,在這種情況下,您可以繼續或中斷。 希望我能解決您的查詢,如果需要進一步說明,請告訴我...
一種可能的方式: 修剪輸入后使用正則表達式。
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);
這實際上有效
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.