2012-03-01 64 views
0

這是我正在處理的問題。JAVA - 用掃描儀讀字符

我們必須要求用戶輸入一個字符串,然後輸入一個字符(任何字符都可以)。然後計算該字符出現在掃描儀中的次數。

我不知道如何添加字符到掃描儀。我們還沒有做陣列尚未所以我不想去那裏,但是這是我迄今所做的:

import java.util.Scanner; 

public class Counter { 

    public static void main (String args[]){ 

     String a; 
     char b; 
     int count; 
     int i; 


     Scanner s = new Scanner (System.in); 


     System.out.println("Enter a string"); 

     a = s.nextLine(); 

     System.out.println("Enter a character"); 

     b = s.next().charAt(0); 

     count = 0; 
     for (i = 0; i <= a.length(); i++){ 

      if (b == s.next().charAt(b)){ 

       count += 1; 

     System.out.println(" Number of times the character appears in the string is " + count); 

       else if{ 

        System.out.println("The character appears 0 times in this string"); 
      } 


      } 

     } 

我知道這是不正確,但現在我不知道這一點。

任何幫助將不勝感激。

+0

我會強烈建議先從代碼*編譯*,即使你想要的但它也許不會那麼做。至少在編譯代碼時,你可以運行它來查看它是否工作。你的代碼只需要一些小的修改來編譯。 – 2012-03-01 02:10:30

回答

1

驗證您的輸入[字符串,字符]使用while循環從用戶獲取字符。基本上你會檢查用戶是否輸入長度爲1的字符串作爲字符輸入。 這裏是編譯運行版本的代碼:

import java.util.Scanner; 

public class Counter 
{ 
    public static void main (String args[]) 
    { 
     String a = "", b = ""; 
     Scanner s = new Scanner(System.in); 

     System.out.println("Enter a string: "); 
     a = s.nextLine(); 
     while (b.length() != 1) 
     { 
      System.out.println("Enter a single character: "); 
      b = s.next(); 
     } 

     int counter = 0; 
     for (int i = 0; i < a.length(); i++) 
     { 
      if (b.equals(a.charAt(i) +"")) 
       counter++; 
     } 
     System.out.println("Number of occurrences: " + counter); 
    } 
} 
0

首先,對循環條件應改爲:

for (i = 0; i < a.length(); i++) 

該指數從0開始,但是當你計數長度從1開始。因此,您不需要'='。

其次,在for循環,你只需要做一兩件事:的每個字符比較B:

if (b == a.charAt(i)) 
    count += 1; 

這裏,與其他解決方案相比,焦炭是價格比字符串進行比較。

三,後for循環,輸出取決於計數:

if (count > 0) 
    System.out.println(" Number of times the character appears in the string is " 
         + count); 
else // must be count == 0 
    System.out.println("The character appears 0 times in this string");