2014-03-05 26 views
0

我有一個家庭作業,需要我編寫一個程序來計算輸入行中的點。到目前爲止,這是我所想出來的(有點),只不過它是在計算一切,而不是點數。我堅持如何讓程序只計算點數。點計數器問題

import javax.swing.*; 
import java.lang.Character; 

public class Assign5_Polk { 
    public static void main(String[] args) { 
     String string = JOptionPane.showInputDialog("Give me dots and i will count them : "); 
     int count = 0; 
     for (int i = 0; i< string.length(); i++) { 
      char c = string.charAt(i); 
      if (string.contains(".")) { 
       count++; 
      } 
     } 
     System.out.println("There are" + " "+ count + " " + "dots" +" " + "in this string. " + string); 
    } 
} 

回答

2

更改if條件如下:

if (string.contains(".")) { // Check whole String contain dot 
count++; 
} 

if (c == '.') { //Check single char of String contain dot 
    count++; 
    } 
0

在你的for循環,反覆測試,如果整個有網點,並增加計數器每一次。你需要像if (c == '.')這樣的東西來確定你正在看的角色是否是一個點。

+0

由於焦炭' '是原始的,你只需要'c =='。'',而不是「.equals」。 –

+0

char沒有等於方法 – Kick

+0

如果您編輯您的帖子,downvoters可能會刪除他們的不良投票。 – csmckelvey

5
if (string.contains(".")) 

該行檢查整個字符串,並在其中任何位置存在.時返回true。

相反,你要測試是否c.

0

解決方案沒有循環;-)

count = string.replaceAll("[^.]","").length(); 

這使得你的程序很短:

public static void main(String[] args) { 
    String string = JOptionPane.showInputDialog("Give me dots and i will count them : "); 
    int count = string.replaceAll("[^.]","").length(); 
    System.out.println("There are "+ count + " dots in this string: " + string); 
} 
+0

@ user3380392你試過了嗎? – donfuxx