我正在尝试用Java读一个句子,并知道那里有多少个单词。这就是我所做的:
public class TestWords {
public static void main(String[] args) {
System.out.println("Give your phrase");
Scanner extr=new Scanner(System.in);
String Phrase;
Phrase = extr.nextLine();
int TotalSizeOfPhrase = Phrase.length();
double number;
for (int i=0; i < TotalSizeOfPhrase; i++)
{
if (Phrase[i] != number && Character.isWhitespace(s.charAt(i)))
{
TotalWords = TotalWords + 1;
}
}
}
}
我想知道如何编写代码:
if (Phrase[i]!= 'of an **arbitrary** number && white space')
然后:
TotalWords = TotalWords + 1;
因为当我输入时它标志着一个错误:
Character.isWhitespace(s.charAt(i))
答案 0 :(得分:2)
有几个错误
Hello i'm 20 and I'm a beginner
20
输入:
5
输出:
public static void main(String[] args) {
System.out.println("Give your phrase");
Scanner extr = new Scanner(System.in);
String Phrase;
Phrase = extr.nextLine();
String[] words = Phrase.trim().split(" ");
System.out.println("Totals Number Of Words: " + words.length);
for (String word : words) {
System.out.println(word.trim());
}
}
答案 1 :(得分:1)
我这样做的方法是用白色空格分割线条(获取单词),将它们添加到数组中,然后获得这个数组长度等于字数。
Phrase = Phrase.trim(); //make sure there is no spaces at start or end of the line
String[] words = Phrase.split(" "); //get the words
int word_count = words.length; //get the word count in line
答案 2 :(得分:0)
如果你想获得句子中的单词数,你可以使用这段代码:
int numberOfWords = Phrase.trim().isEmpty() ? 0 : trim.split("\\s+").length;
答案 3 :(得分:0)
您可以使用此代码:
import { inject } from 'aurelia-framework';
import { DialogController } from 'aurelia-dialog';
import { ValidationController, ValidationRules } from 'aurelia-validation';
import { MaterializeFormValidationRenderer } from './../resources/elements/materialize-form-validation-renderer';
@inject(DialogController, ValidationController)
export class AddProject {
rules = ValidationRules
.ensure('name')
.required()
.withMessage('Please enter a name for your project.')
.rules;
constructor(dialogController, validationController) {
this.name = '';
this.project = null;
this.dialogController = dialogController;
this.validationController = validationController;
this.validationController.addRenderer(new MaterializeFormValidationRenderer());
}
activate(project) {
this.project = project;
}
detached() {
this.validationController.reset();
}
validateModel() {
return new Promise((resolve, reject) => {
this.validationController.validate().then(v => {
resolve(v.valid);
});
}, function (error) {
reject(error);
});
}
validateProject(e) {
this.validateModel().then(valid => {
if (valid) {
this.project.name = this.name;
this.name = '';
//this.validationController.reset();
this.dialogController.ok(this.project);
}
});
}
cancel(e) {
this.name = '';
//this.validationController.reset();
this.dialogController.cancel();
}
}