2014-11-25 284 views
1

所以我一直在用Java編寫一小段代碼,它從用戶輸入大寫,小寫和其他部分(如空格,數字,甚至是括號),然後返回每個用戶都有很多。大寫字母,小寫字母和其他計數器

我現在的問題是說我在「你好」的位置放置了「你好」後面的「o」後停止計數點。所以在第一個字之後。

代碼

import java.util.Scanner; 

public class Example { 

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    int upper = 0; 
    int lower = 0; 
    int other = -1; 
    int total = 0; 
    String input; 
    System.out.println("Enter the phrase: "); 
    input = scan.next(); 
    for (int i = 0; i < input.length(); i++) { 
     if (Character.isUpperCase(input.charAt(i))) upper++; 
     if (Character.isLowerCase(input.charAt(i))) lower++; 
     else other++; 
     total = upper + lower + other; 
    } 
    System.out.println("The total number of letters is " + total); 
    System.out.println("The number of upper case letters is " + upper); 
    System.out.println("The number of lower case letters is " + lower); 
    System.out.println("The number of other letters is " + other); 
} 
} 

回答

2

Scanner#next

查找並返回來自此掃描器的下一個完整標記。 A 完整令牌的前後是與 定界符模式匹配的輸入。

問題是next沒有看到「There」這個詞,因爲「Hello World」不是一個完整的標記。

next更改爲nextLine

建議:使用調試器,您會很快發現問題,當您懷疑引用文檔時,它們就在您身邊。

+0

謝謝你,我甚至沒有看到的一切事物。 – 2014-11-25 13:22:26

0

您需要更改next()nextLine() - 它會讀取所有的行

1

問題是,next()只返回行了空間之前,但nextLine()將讀取整條生產線。

所以更改

scan.next(); 

scan.nextLine(); 
0

正如其他人說。您應該從scn.next更改爲scn.nextLine()。但爲什麼?這是因爲scn.next()只能讀取,直到遇到空格,並停止閱讀。因此,空格之後的任何輸入都不會被讀取。

scn.nextLine()讀取,直到遇到換行符(即enter)。

0

您可以使用正則表達式嘗試:

public static void main(String[] args) { 
    String input = "Hello There"; 
    int lowerCase = countMatches(Pattern.compile("[a-z]+"), input); 
    int upperCase = countMatches(Pattern.compile("[A-Z]+"), input); 
    int other = input.length() - lowerCase - upperCase; 
    System.out.printf("lowerCase:%s, upperCase:%s, other:%s%n", lowerCase, upperCase, other); 
} 

private static int countMatches(Pattern pattern, String input) { 
    Matcher matcher = pattern.matcher(input); 
    int count = 0; 
    while (matcher.find()) { 
     count++; 
    } 
    return count; 
} 
相關問題