我的代码有问题。我知道它必须与Count构造函数及其参数做一些事情。但是,我无法全神贯注。
我应该在Count构造函数中添加哪些参数以使代码正常工作?
import java.util.Scanner;
public class CH9Assignment
{
public static void main (String [] args)
{
count();
//Create Scanner object
Scanner input = new Scanner (System.in) ;
System.out.println ("Enter a sentence:");
String s1 = input.nextLine();
System.out.println ("Enter 1 to count characters, 2 to count words");
int x = input.nextInt();
if (x == 1)
System.out.println ("There are " + s1.length() + "characters");
}
public static int count(String word)
{
if (word == null || word.isEmpty())
{
return 0;
}
int wordCount = 0;
boolean isWord = false;
int endOfLine = word.length() - 1;
char[] characters = word.toCharArray();
for (int i = 0; i < characters.length; i++)
{
if (Character.isLetter(characters[i]) && i != endOfLine)
{
isWord = true;
}
else if (!Character.isLetter(characters[i]) && isWord)
{
wordCount++; isWord = false;
}
else if (Character.isLetter(characters[i]) && i == endOfLine)
{
wordCount++;
}
if (x == 2)
System.out.println ("There are " + wordCount + "words");
}
}
}
答案 0 :(得分:1)
您只有一个称为count的方法,它需要一个String参数,但是您尝试不使用参数来调用它。
import java.util.Scanner;
public class CH9Assignment
{
public static void main (String [] args)
{
// count(); --> DELETE THIS CALL, you don't have such a method
//Create Scanner object
Scanner input = new Scanner (System.in) ;
System.out.println ("Enter a sentence:");
String s1 = input.nextLine();
int result = count(s1); // ADD THIS LINE
System.out.println ("Enter 1 to count characters, 2 to count words");
int x = input.nextInt();
if (x == 1)
System.out.println ("There are " + s1.length() + "characters");
}
// Your count method
}
这将解决编译问题。您应该能够解决逻辑问题。
答案 1 :(得分:0)
您必须使用某些内容作为参数来调用count
方法。因此,只需在if块内使用s1
作为参数来调用它。您的count
方法似乎也太大了,被炸了。因此,我对其进行了更改,以通过简单的正则表达式将字符串拆分。尝试以下代码段:
public static void main (String [] args){
//Create Scanner object
Scanner input = new Scanner (System.in) ;
System.out.println ("Enter a sentence:");
String s1 = input.nextLine();
System.out.println ("Enter 1 to count characters, 2 to count words");
int x = input.nextInt();
switch(x){
case 1;
System.out.println ("There are " + s1.length() + " characters");
return;
case 2:
System.out.println ("There are " + count(s1) + " words");
return;
}
}
public static int count(String word){
if(word == null || word.isEmpty()){
return 0;
}
return word.split("(\\s|\\S)+").length;
}