因此,該程序應該做的是,用戶輸入一個字符串,程序將檢查charAt(0)中的每個字符, charAt(字符串的長度 - 1) 它將檢查它是否是有效的字母(AZ或az)。任何非字母都被視爲字詞分隔符。Java如何根據用戶輸入創建數組長度以及如何爲數組指定數值
每當下一個字符是字母時,計數器就會遞增。一旦字符無效(數字,符號,標點符號,空格等)以及無效字符到最後一個有效字符(在本例中爲charAt(0))的字符之前,計數器將重置爲0將創建字1。該字符無效,它會將計數器分配給一個最初以索引0開始的數組,然後將索引遞增,以便將其分配給下一個字長。
如何根據此程序中創建的字數創建一個數組?例如,如果輸入以下字符串,數組的長度將爲7.
什麼是8this pro98gram doin8g? Word1 =什麼,Word2 =是,Word3 =這,Word4 =親,Word5 =克,Word6 =幹,Word7 = g。
另外,如何將數值賦給特定的數組索引,例如字[a],其中a是0,1,2,3,4等,每次進入else語句時該程序。
這是我迄今爲止所做的。
import java.util.Scanner;
public class WordCountInString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = 0; // Initial index is 0;
int[] word = new int[a]; // Creating an array.
String string;
System.out.print("Enter a String of Data Please: ");
string = input.nextLine();
int counter = 0;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) >= 'a' && string.charAt(i) >= 'z' // Check to see if charAt(i) is a letter.
|| string.charAt(i) >= 'A' && string.charAt(i) <= 'Z') {
counter++; // Counter every time the next char is a letter.
}
else {
word[a] = counter; // Assign the array of index(a) to counter
a++; // Go to the next index.
counter = 0; // Reset the counter to create a new word.
}
}
for (int j = 0; j < word.length; j++) { //Prints out all the arrays.
System.out.println(word[j]); // Print the value of each array.
}
}
}
很可能你必須經過兩次字符串 - 第一次你會確定有多少單詞。你可以通過計算非字母的數量來做到這一點。然後,如果'n'是單詞的數量,那麼你可以根據你需要做的事情來創建'new int [n]'或'new String [n]'。如果你被允許使用'ArrayList',那會更好,因爲你事先不需要知道它有多大。但是如果你必須使用一個數組,這將是一種方法。 – ajb
我還沒有學習接口,所以我不能使用接口。但是在運行程序時出現錯誤。這是爲什麼? – Majestic
@Majestic也許你應該告訴我們你的代碼有哪些錯誤可以幫助你。 – AxelH