JAVA 算字數多少

Get an input word from the user, and print the character that appears

most often in the word. (If there are several characters that tie for the

biggest count, you may print any of those characters.)

example:

enter a word:banana

a appears 3 times in banana

2 Answers

Rating
  • 1 decade ago
    Favorite Answer

    請參考我的做法

    import java.util.*;public class Y4237 { public static void main(String[] args) { System.out.print("Please enter a word: "); Scanner scan = new Scanner(System.in); String s = scan.next(); char[] ary = s.toCharArray(); char c = 'a', cTemp = ary[0]; int count = 0, countTemp = 0; Arrays.sort(ary); for (char ch: ary) { if (ch == cTemp) { countTemp++; if (countTemp > count) { c = cTemp; count = countTemp; } } else { cTemp = ch; countTemp = 1; } } System.out.println(c + " appears " + count + " time(s) in " + s); }}

  • 志明
    Lv 5
    1 decade ago

    原本想說很複雜不想寫的,不過還是寫了

    因為這種題目沒寫過,呵

    又死了幾十萬隻的腦細胞 Orz

    import java.util.*;

    public class Test888 {

    public static void main(String[] args) {

    Map map = new HashMap();

    Map maxmap = new HashMap();

    Scanner scanner = new Scanner(System.in);

    System.out.print("enter a word:");

    String str = scanner.next();

    char[] ch = str.toCharArray();

    int max = 0;

    for (char c : ch) {

    int count = 0;

    for (char cc : ch) {

    if (c == cc) {

    count ;

    }

    }

    if (count > max) {

    max = count;

    }

    map.put(c, count);

    }

    Set set = map.keySet();

    for (Iterator it = set.iterator(); it.hasNext();) {

    Object o = it.next();

    if ((Integer) map.get(o) == max) {

    maxmap.put(o, map.get(o));

    }

    }

    set = maxmap.keySet();

    for (Iterator it = set.iterator(); it.hasNext();) {

    Object o = it.next();

    System.out.println(o " appears " map.get(o) " times in " str);

    }

    }

    }

    2008-10-24 15:26:57 補充:

    被吃字…這裡是這樣子的

    if (c == cc) {

    count++;

    }

    還有最後一行

    System.out.println(o+ " appears "+ map.get(o)+ " times in "+ str);

    2008-10-24 15:27:42 補充:

    我打的+是全形的哦…你自已改成半形的即可

    Source(s): myself
Still have questions? Get your answers by asking now.