寻找基本阵列问题的帮助。程序必须读取一个句子并将字长的频率存储在一个数组中,然后打印出多少个单词是1个字母单词,2个字母单词等。
我是一个非常原始的java程序员,但是在下面做了一下就会非常感谢一些指导。我运行程序并输入一个句子时似乎编译但是吐出一些乱码十六进制。
当我在程序中输入一个句子时,我得到一个输出,如下所示:
[I@eb42cbf
[I@eb42cbf
[I@eb42cbf
[I@eb42cbf
[I@eb42cbf
[I@eb42cbf
我的代码:
class WordCount
{
public static void main(String[] args)
{
int wordList[] = new int[20];
System.out.println("Please enter a sentence.");
for (int i = 0; i <= wordList.length; i++)
{
String s = Console.readToken();
int x = s.length();
wordList[x]++;
}
int x = 1;
while (x < wordList.length)
{
if (wordList[x] > 0)
System.out.println(x + "-letter words: " + wordList[x]);
x++;
}
}
}
答案 0 :(得分:3)
以下是我的建议:
这是我的版本 - 更改包括:使用扫描仪,将x重命名为i并将while循环更改为for循环:
public static void main(String[] args) {
int wordList[] = new int[20];
System.out.println("Please enter a sentence.");
Scanner scanner = new Scanner(System.in); //Use a scanner, part of the standard JDK
for (int i = 0; i <= wordList.length; i++) {
String s = scanner.next(); //reads the next string
int length = s.length();
wordList[length]++;
}
for (int i = 0; i < wordList.length; i++) { //use a for loop
if (wordList[i] > 0) {
System.out.println(i + "-letter words: " + wordList[i]);
}
}
}
答案 1 :(得分:1)
while循环不应该
while(i < wordlist.Length){
if (wordlist[i] > 0){
System.out.println(i + "-letter words: " + wordlist[i]);
}
i++;
}
答案 2 :(得分:0)
private static long wordcount(String line){
long numWords = 0;
int index = 0;
boolean prevWhiteSpace = true;
while(index < line.length()){
char c = line.charAt(index++);
boolean currWhiteSpace = Character.isWhitespace(c);
if(prevWhiteSpace && !currWhiteSpace){
numWords++;
}
prevWhiteSpace = currWhiteSpace;
}
return numWords;
}
答案 3 :(得分:0)
如果你的意思是当输入一个句子时:“这是一个句子”,输出应该是:
4个字母的单词:2
2个字母的单词:1
1个字母的单词:1
8个字母的单词:1
我的代码:
import java.util.HashMap;
import java.util.Scanner;
class WordCount {
public static void main(String[] args) {
HashMap<Integer, Integer> statistic = new HashMap<Integer, Integer>();
System.out.println("Please enter a sentence.");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
String[] words = s.split(" ");
for (int i = 0; i < words.length; i++) {
if (statistic.containsKey(words[i].length())) {
Integer value = statistic.get(words[i].length());
statistic.put(words[i].length(), value + 1);
} else
statistic.put(words[i].length(), 1);
}
for (Integer num : statistic.keySet()) {
Integer key = num;
Integer value = statistic.get(num);
System.out.println(key + "-letter words: " + value);
}
}
}
答案 4 :(得分:0)
又一种方法:
int wordList[] = new int[20];
System.out.println("Please enter a sentence.");
String s = "";
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
s = bufferRead.readLine();
}
catch(IOException e){
e.printStackTrace();
}
String[] s1 = s.split(" ");
for(int i = 0 ; i < s1.length ; i++){
int len = s1[i].length();
wordList[len]++;
}
for (int i = 0; i < wordList.length; i++) { //use a for loop
if (wordList[i] > 0) {
System.out.println(i + "-letter words: " + wordList[i]);
}
}