Java元音字母计数替代方法

huangapple go评论66阅读模式
英文:

Java Vowel Counter Alternative Method

问题

以下是翻译后的内容:

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    int A = 0, E = 0, I = 0, O = 0, U = 0;

    System.out.print("输入一个单词 > ");
    String word = input.next();

    for (int i = 0; i < word.length(); i++) {
      String s = word.substring(i, i + 1);

      if (s.equalsIgnoreCase("A")) { A++; } 
      else if (s.equalsIgnoreCase("E")) { E++; }
      else if (s.equalsIgnoreCase("I")) { I++; }
      else if (s.equalsIgnoreCase("O")) { O++; }
      else if (s.equalsIgnoreCase("U")) { U++; } 
    }

    int total = A + E + I + O + U;
    System.out.println("\n'" + word + "' 中有...\n" + A + " 个 A\n" + E + " 个 E\n" + I + " 个 I\n" + O + " 个 O\n" + U + " 个 U\n总计元音数量: " + total + "\n");

    input.close();
  }
}

输入:

Coding

输出:

'Coding' 中有...
0 个 A
0 个 E
1 个 I
1 个 O
0 个 U
总计元音数量: 2
英文:

I'm writing a simple vowel-counter and was wondering if there's a cleaner alternative (possibly a loop?) to replace all of the else if's when comparing s to the various vowels.

I can't think of a simple way to do this effectively as the number of each vowel must be shown individually. It would be very simple if it was just a total vowel count.

I'm quite new to Java so I don't know what can be used to clean this up. If this is the best option, then I am contempt -- but I love cleaning up code where it can be!

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    int A = 0, E = 0, I = 0, O = 0, U = 0;

    System.out.print(&quot;Type a single word &gt; &quot;);
    String word = input.next();

    for (int i = 0; i &lt; word.length(); i++) {
      String s = word.substring(i, i + 1);

      if (s.equalsIgnoreCase(&quot;A&quot;)) { A++; } 
      else if (s.equalsIgnoreCase(&quot;E&quot;)) { E++; }
      else if (s.equalsIgnoreCase(&quot;I&quot;)) { I++; }
      else if (s.equalsIgnoreCase(&quot;O&quot;)) { O++; }
      else if (s.equalsIgnoreCase(&quot;U&quot;)) { U++; } 
    }

    int total = A + E + I + O + U;
    System.out.println(&quot;\n&#39;&quot; + word + &quot;&#39; has...\n&quot; + A + &quot; A&#39;s\n&quot; + E + &quot; E&#39;s\n&quot; + I + &quot; I&#39;s\n&quot; + O + &quot; O&#39;s\n&quot; + U + &quot; U&#39;s\nTotal vowels: &quot; + total + &quot;\n&quot;);

    input.close();
  }
}

Input:

Coding

Output:

&#39;Coding&#39; has...
0 A&#39;s
0 E&#39;s
1 I&#39;s
1 O&#39;s
0 U&#39;s
Total vowels: 2

答案1

得分: 3

以下是一个不那么重复的编码方式,使用一个整数数组来存储计数,以及一个字符串来保存元音序列。

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("输入一个单词 > ");
        String word = input.next();
        String vowels = "AEIOU";
        int[] counts = new int[vowels.length()];
        int total = 0;
        for (int i = 0; i < word.length(); i++) {
            int index = vowels.indexOf(Character.toUpperCase(word.charAt(i)));
            if (index >= 0) {
                ++counts[index];
                ++total;
            }
        }
        System.out.printf("%n'%s' 具有...%n", word);
        for (int i = 0; i < counts.length; ++i) {
            System.out.printf("%s %s's%n", counts[i], vowels.charAt(i));
        }
        System.out.printf("元音总数:%s%n", total);
    }
}

输出:

输入一个单词 > Coding

'Coding' 具有...
0 A's
0 E's
1 I's
1 O's
0 U's
元音总数:2
英文:

Here is a less repetitive way to code it, using an int array for the counts, and a string holding the sequence of vowels.

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print(&quot;Type a single word &gt; &quot;);
        String word = input.next();
        String vowels = &quot;AEIOU&quot;;
        int[] counts = new int[vowels.length()];
        int total = 0;
        for (int i = 0; i &lt; word.length(); i++) {
            int index = vowels.indexOf(Character.toUpperCase(word.charAt(i)));
            if (index &gt;= 0) {
                ++counts[index];
                ++total;
            }
        }
        System.out.printf(&quot;%n&#39;%s&#39; has...%n&quot;, word);
        for (int i = 0; i &lt; counts.length; ++i) {
            System.out.printf(&quot;%s %s&#39;s%n&quot;, counts[i], vowels.charAt(i));
        }
        System.out.printf(&quot;Total vowels: %s%n&quot;, total);
    }
}

Output:

Type a single word &gt; Coding

&#39;Coding&#39; has...
0 A&#39;s
0 E&#39;s
1 I&#39;s
1 O&#39;s
0 U&#39;s
Total vowels: 2

答案2

得分: 0

你可以通过使用一个Map来避免大量的重复,该Map将元音字母(键)与在运行时传递的word中的频率(值)关联起来。

值得注意的是,在下面的示例中使用了LinkedHashMap,以保留键的插入顺序,以便在程序末尾打印出来,而使用HashMap则不会保留插入顺序。

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // 定义Map以将元音字母映射到频率
        Map<Character, Integer> vowels = new LinkedHashMap<Character, Integer>();
        vowels.put('A', 0);
        vowels.put('E', 0);
        vowels.put('I', 0);
        vowels.put('O', 0);
        vowels.put('U', 0);

        // 从用户获取输入
        System.out.print("输入一个单词 > ");
        String word = input.next();

        // 遍历单词
        for (int i = 0; i < word.length(); i++) {
            String c = word.substring(i, i+1); // 获取当前字符
            for (Character key : vowels.keySet()) { // 遍历元音字母
                if (c.equalsIgnoreCase(key.toString()))  {
                    vowels.put(key, vowels.get(key)+1); // 如果匹配,则增加元音字母的频率
                    break; // 中断内部循环并移动到单词中的下一个字符
                }
            }
        }
        
        // 计算总数
        int total = 0;
        for (Character key : vowels.keySet()) {
            total += vowels.get(key);
        }

        // 将结果打印到控制台
        System.out.println("'" + word + "'" + " 中...");
        for (Character key : vowels.keySet()) {
            System.out.println(vowels.get(key) + " 个 " + key + " 的");
        }
        System.out.println("元音字母总数:" + total);

        input.close();
    }
}
英文:

You could avoid a lot of repetition by using a Map that associates vowels (keys) to their frequencies within the word passed at runtime (values).

It is worth noting that a LinkedHashMap is used in the below example as to preserve the insertion order of keys for printing at the end of the program - as would not be the case with a HashMap.

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		
		// Define Map to map vowels to frequencies
		Map&lt;Character, Integer&gt; vowels = new LinkedHashMap&lt;Character, Integer&gt;();
		vowels.put(&#39;A&#39;, 0);
		vowels.put(&#39;E&#39;, 0);
		vowels.put(&#39;I&#39;, 0);
		vowels.put(&#39;O&#39;, 0);
		vowels.put(&#39;U&#39;, 0);
		
        // Get input from user
		System.out.print(&quot;Type a single word &gt; &quot;);
		String word = input.next();
		
		// Iterate across word 
		for (int i = 0; i &lt; word.length(); i++) {
		  String c = word.substring(i, i+1); // Get current char
		  for (Character key : vowels.keySet()) { // Iterate across vowels
			  if (c.equalsIgnoreCase(key.toString()))  { 
				  vowels.put(key, vowels.get(key)+1); // Increment vowel frequency if matched
				  break; // Break inner loop and move to next char in word
		  }
		}
		// Sum total
		int total = 0;
		for (Character key : vowels.keySet()) {
		total += vowels.get(key);
		}
		
		// Print results to console
		System.out.println(&quot;\&#39;&quot; + word + &quot;\&#39;&quot; + &quot; has...&quot;);
		for (Character key : vowels.keySet()) {
		System.out.println(vowels.get(key) + &quot; &quot; + key + &quot;\&#39;s&quot;);
		}
		System.out.println(&quot;Total vowels: &quot; + total);
		
		input.close();
	  }
	}
}

huangapple
  • 本文由 发表于 2020年9月29日 21:18:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64120462.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定