[英]How can I make 'Split' and 'wordCount' methods work together?
我是Java的初學者,是計算機科學的一年級學生,對Java的理解非常薄弱,並且在理解其結構方面存在很多問題。
這是我到目前為止的代碼:
import java.util.*;
public class hdtest1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s;
while(true)
{
System.out.println("Enter value:");
s=sc.next();
if(s.equals("quit"))
{
break;
}
String[] s = string.split(" ");
int wordCount = 1;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' '&& str1.charAt(i+1)!=' ')
{
wordCount++;
}
}
}
}
System.out.println(""+s); //to Print string
System.out.println(""+s.length()); //to print Entered string's length
System.out.println("Word count is = " +(str1.length()- wordCount));
}
我希望我的java輸出顯示在文本窗口(掃描儀)中輸入的文本行,總字符數以及每個單詞的字符數。 例如,當用戶輸入“ Hello,我的名字是Mark”時,我正在尋找的輸出是:
Hello, my name is Mark
22
Hello = 5
my = 2
name = 4
is = 2
Mark = 4
//Here the scanner loops,appears and is ready for more text to be entered
因此,總結一下我的問題-請您更正錯誤所在的代碼,以使其正常工作並輸出我想要的代碼(如上所示)? 非常感謝您的幫助,我們將不勝感激。
目前,我的代碼顯示許多錯誤,它們是結構性錯誤,因為我對將不同的方法配合在一起的了解甚少。 到目前為止,我發現了很多我認為可以一起工作的代碼塊,並且我嘗試使用這些代碼進行操作以使方法一起工作,但是我似乎只是使我的代碼變得更糟,因為我不了解許多代碼的含義錯誤,以便能夠糾正它們。 我的代碼運行良好,直到我開始嘗試使用“ split”方法拆分在掃描儀中輸入的單詞。
以下是錯誤的快速列表,供您查看:
第15行-重復變量s,
第15行-無法解析字符串,
第18行-無法解析str1,
第20行-str1無法解析,
第28行-令牌語法錯誤,構造位置錯誤,
第28行-令牌“ println”上的語法錯誤,=預期在此令牌之后,
第29行-令牌語法錯誤,構造位置錯誤,
第30行-令牌語法錯誤,構造位置錯誤,
第30行-令牌“ println”上的語法錯誤,=此令牌后應有的錯誤,
看來您只想要這個:
int wordCount = string.split(" ").length;
如果要打印單詞及其長度:
for (String word : string.split(" "))
System.out.println(word + " = " + word.length());
從掃描儀獲得輸入后(假設它是一個稱為input
的變量),請嘗試:
// The line below splits the sentence into individual tokens by spaces, and puts them into an array
String[] allWords = input.split(" ");
System.out.println(input);
System.out.println(input.length()); // Get number of characters in input
for (int i = 0; i < allWords.length; i++) { // Loop through each word
String word = allWords[i].replaceAll("[^a-zA-Z]", ""); // This uses a regex to eliminate anything but letters and puts the word into a variable "word"
System.out.println(word + " = " + word.length()); // Output the word and the length
}
將此代碼塊放入掃描儀讀取一行的循環中。
僅需注意,length()方法輸出字符串中的字符數,包括空格。 這就是為什么我們在輸出長度時除去字母以外的所有其他字符的原因。
將一個句子拆分成多個組成詞,然后只需在每個詞上調用length()方法即可獲得字符數。
String[] words = input.split("\\s+"); // get the individual words (separated by white space)
System.out("#words = " + words.length);
for (int i = 0; i < words.length; i++)
System.out("word[" + i + "]: " + words[i] + " nchars = " + words[i].length());
幾個指針:
您有一個String和一個String [],您不能這樣做,請重命名其中之一。
“ str1”在哪里? 尚未聲明或初始化。
3。
System.out.println(""+s);
“ s”已經是一個字符串,“” +是不必要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.