在给我上课时要解决的一个问题,我需要输入一个字符串,然后打印出该字符串中有多少个数字。单词被定义为仅包含字符a-z和A-Z。我不能使用split()。
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String sentence;
String currentWord;
int wordCount;
int spacePos;
int validChar;
System.out.print("Please enter a sentence: \n");
sentence = input.nextLine() + " ";
spacePos = sentence.indexOf(" ");
wordCount = 0;
currentWord = sentence.substring(0, spacePos);
validChar = 0;
while(spacePos > -1)
{
for(int i = 0; i < currentWord.length(); i++)
{
int j = currentWord.charAt(i);
if( j >= 'a' && j <= 'z' || j >= 'A' && j <= 'Z')
{
validChar++;
}
}
if( validChar == currentWord.length() )
{
wordCount++;
}
currentWord = currentWord.substring(spacePos);
}
System.out.println("The number of words in this string is " + wordCount + "\n\n");
input.close();
}
}
}
这是我到目前为止的内容,但我收到一个错误,说currentWord = currentWord.substring(spacePos);
是
java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-5
编辑:我的问题不仅与错误有关,而且与逻辑有关,但我花了好几个小时在纸上并将其从头重写并解决了。这是我未使用.split()
的更新代码。
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String currentWord;
String sentence;
int spacePos;
int wordCount;
int validChar;
System.out.print("Please enter a sentence: \n");
sentence = input.nextLine() + " ";
spacePos = sentence.indexOf(" ");
currentWord = sentence.substring(0, spacePos);
wordCount = 0;
validChar = 0;
if( spacePos == 0 )
{
spacePos = 1;
}//end of if
for( int i = 0; i < sentence.length(); i++ )
{
// VALIDATES IF A WORD IS A WORD
for(int j = 0; j < currentWord.length(); j++)
{
if( currentWord.charAt(j) > 'a' && currentWord.charAt(j) < 'z'
|| currentWord.charAt(j) > 'A' && currentWord.charAt(j) < 'Z')
{
validChar++;
}//end of if
if( validChar == currentWord.length() )
{
validChar = 0;
wordCount++;
}//end of if
}//end of for
// ROMOVES PREVIOUS WORD
sentence = sentence.replace(currentWord + " ", "");
currentWord = sentence.substring(0, spacePos);
spacePos = sentence.indexOf(" ") + 1;
} //end of for
System.out.println("\n\n FINAL WORD COUNT --->\t\t" + wordCount + "\n");
input.close();
}
答案 0 :(得分:-1)
下面的逻辑应该对您有用,
public static void main(String[] args)
{
int wordCount=0;
StringBuffer newDummy=new StringBuffer();
String dummy = "1223fgfdfsdfhi sdfsdfh8678 df 435";
for(int i = 0; i < dummy.length(); i++)
{
if (Character.isDigit(dummy.charAt(i)))
{
wordCount++;
}else{
newDummy.append(dummy.charAt(i));
}
}
System.out.println("The number of words in this string is " + wordCount + "\n\n");
System.out.println("new String-->"+newDummy);
}