Мне дали задачу решить в классе, где мне нужно взять строку, а затем распечатать, сколько чисел в строке. Слово определяется как содержащее только символы 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: String index out of range: -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();
}
Возможный дубликат Что вызывает исключение java.lang.ArrayIndexOutOfBoundsException и как его предотвратить?




Логика ниже должна работать для вас,
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);
}
Вы отлаживали через это?