2016-02-26 70 views
0

与标题相同。我的代码应该给出答案[1,3,3,1,0],但我无法让它给我任何控制台输出。我单独计算元音的代码不会给出我需要的值。它应该返回array.toString(),但不会

public static void main(String[] args) { 
     vowelCount("i think therefore i am"); 
    } 

    public static int[] vowelCount(String sentence) { 
     int[] vowelsCounted = new int[5]; 
     vowelsCounted.toString(); 
     for (int i=0; i<sentence.length(); i++) { 
     char ch = sentence.charAt(i); 
     if (ch == 'a') { 
      vowelsCounted[0]++; 
     } else if (ch == 'e') { 
      vowelsCounted[1]++; 
     } else if (ch == 'i') { 
      vowelsCounted[2]++; 
     } else if (ch == 'o') { 
      vowelsCounted[3]++; 
     } else if (ch == 'u') { 
      vowelsCounted[4]++; 
     } 
     } 
     return vowelsCounted; 
    } 
} 

我需要一些关于如何做以及为什么它不会给我答案的建议。 编辑:这已被回答,我正在使用错误的类。它已被更改为:

import java.util.Arrays; 

public class Exercise17 { 

    public static void main(String[] args) { 
     System.out.println(vowelCount("i think therefore i am")); 
    } 

    public static String vowelCount(String sentence) { 
     int[] vowelsCounted = new int[5]; 
     vowelsCounted.toString(); 
     for (int i=0; i<sentence.length(); i++) { 
     char ch = sentence.charAt(i); 
     if (ch == 'a') { 
      vowelsCounted[0]++; 
     } else if (ch == 'e') { 
      vowelsCounted[1]++; 
     } else if (ch == 'i') { 
      vowelsCounted[2]++; 
     } else if (ch == 'o') { 
      vowelsCounted[3]++; 
     } else if (ch == 'u') { 
      vowelsCounted[4]++; 
     } 
     } 
     return Arrays.toString(vowelsCounted) ; 

    } 
} 
+0

我也想提一提,这是构建Java程序3第7章练习17,只是这些信息是非常有用的情况。 –

+1

不明白你的意思应该返回array.toString()' - 你在哪里调用它? –

+0

我的意思是说,我的方法vowelCount运行一个过程来获取一个字符串,检测字符,如果它是一个元音,那么vowelsCounted [0或1或2或3或4] ++。该数组在底部返回。这本书说,我称之为“我认为我是”的参数的方法应返回相当于vowelsCounted.toString()的方法。 –

回答

0

那么,你是想为

public static String vowelCount(String sentence) { 
     int[] vowelsCounted = new int[5]; 
     vowelsCounted.toString(); 
     for (int i=0; i<sentence.length(); i++) { 
     char ch = sentence.charAt(i); 
     if (ch == 'a') { 
      vowelsCounted[0]++; 
     } else if (ch == 'e') { 
      vowelsCounted[1]++; 
     } else if (ch == 'i') { 
      vowelsCounted[2]++; 
     } else if (ch == 'o') { 
      vowelsCounted[3]++; 
     } else if (ch == 'u') { 
      vowelsCounted[4]++; 
     } 
     } 
     return Arrays.toString (vowelsCounted); 
    } 
+0

工作正常!非常感谢!在你之前,我已经用了45分钟的目光呆呆了。祝你有美好的一天! –

0

你想要什么Arrays.toString(INT [])方法:

没有为每一个不同的原始的Java类型的静态Arrays.toString helper方法;用于int []的说明如下:

public static String toString(int[] a) 

返回指定数组内容的字符串表示形式。字符串表示由数组元素的列表组成,方括号(“[]”)。相邻元素由字符“,”分隔(逗号后跟空格)。通过String.valueOf(int)将元素转换为字符串。如果a为null,则返回“null”。

+0

确实 public static String vowelCount(String sentence) 与我的其他代码有相同的影响。我申请了这个,一切都变红了。 –

+0

在你的情况下,你必须将'vowelsCounted.toString()'替换为'Arrays.toString(vowelsCounted)'并且导入相应的包java.util.Arrays' –

+0

就是这样。谢谢! –

相关问题