2016-03-21 44 views
1
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.PrintWriter; 
import java.util.Scanner; 


public class Vowels 
{ 
public static void main(String[] args) throws FileNotFoundException 
    { 
    String vowels = "aeiou"; 
    int[] counters = new int[vowels.length()]; 

    Scanner console = new Scanner(System.in); 
    System.out.print("Input file: "); 
    String inputFileName = console.next(); 

    console.useDelimiter(""); 
    while (console.hasNext()) 
    { 

     char ch = console.next().charAt(0); 
     ch = Character.toLowerCase(ch); 
     if(ch == 'a') 
     { 
      counters[0]++; 
     } 
     if(ch == 'e') 
     { 
      counters[1]++; 
     } 
     if(ch == 'i') 
     { 
      counters[2]++; 
     } 
     if(ch == 'o') 
     { 
      counters[3]++; 
     } 
     if(ch == 'u') 
     { 
      counters[4]++; 
     } 
    } 




    for (int i = 0; i < vowels.length(); i++) 
    { 
    System.out.println(vowels.charAt(i) + ": " + counters[i]); 
    } 

    } 
} 

當我運行這些文件時,它會檢測到3 e只有當它應該檢測到兩個都是幾百個時。我沒有看到任何問題,我的代碼會導致問題,請幫助。我假設它必須介於我的分隔符和結尾之間,因爲其餘部分不在本書中。字符不增加while循環中的數組計數器?

+0

您是否嘗試過在while循環中放置'System.out.println(ch);'來查看它是否在做正確的事情?這可能有助於弄清楚。 –

+2

更重要的是,你有沒有嘗試過'String term = console.next();的System.out.println(術語); ch = term.charAt(0);'確定你的'useDelimiter(「」);'是否實際上每次給你一個字符? – AJNeufeld

回答

1

您的分隔符不符合您的想法。假設您打算從inputFileName中讀取,您可以構建一個FileScanner(記住要在finally塊中或try-with-resources statement中關閉Scanner)。您還可以通過vowels元音的位置確定正確的counters索引。最後,你可以使用格式化的io作爲輸出循環。類似的,

String vowels = "aeiou"; 
int[] counters = new int[vowels.length()]; 

Scanner console = new Scanner(System.in); 
System.out.print("Input file: "); 
String inputFileName = console.nextLine().trim(); 
try (Scanner scan = new Scanner(new File(inputFileName))) { 
    while (scan.hasNextLine()) { 
     for (char ch : scan.nextLine().toLowerCase().toCharArray()) { 
      int p = vowels.indexOf(ch); 
      if (p >= 0) { 
       counters[p]++; 
      } 
     } 
    } 
} 
for (int i = 0; i < vowels.length(); i++) { 
    System.out.printf("%c: %d%n", vowels.charAt(i), counters[i]); 
} 
0

有2個問題,在你的代碼,

  1. 當你使用console.next();輸入已分配給inputFileName。這隻留下回車(\r\nconsole
  2. 既然你給new Scanner(System.in),你的程序將等待用戶輸入更多的輸入,永遠不會結束。 console.hasNext()永遠不會是假的。

你能做些什麼,在while循環從inputFileName得到每一個字符,然後遞增元音數量。

如果你想從一個文件的輸入,你應該做的

File file = new File(<path to file>); 
Scanner sc = new Scanner(file); 

然後while循環會工作。請記住在閱讀文件後關閉console