Я уверен, что мой вопрос мог бы быть лучше, так что заранее извините.У меня есть проект Java, который я пытаюсь проанализировать текст в строке.Я хотел бы посчитать 3 числа и добавить их, посчитать слова, которые начинаются с а, и отобразить его.подсчитайте слова, которые заканчиваются на «s» или «s», подсчитайте общее количество слов и, наконец, посчитайте предложения. До сих пор я был в состоянии сделать все, кроме когда я запускаю программу, дисплей довольно перемешан. В идеале яЯ хотел бы сохранить каждый раздел вместе, но по какой-то причине я не могу этого добиться.
import java.util.Arrays;
class TextAnalysisHW {
public static void main(String[] args) {
String text = "This is a long string that contains numbers like 100, 34.0, 21 and odd symbols like &, %, #. We are supposed to determine how many words this string has in it and also the number of sentences. We are also required to determine how many numbers are in it and sum them all up. Finally, we must count and display all the words that end with a 's' and start with an 'a'.";
// create a copy of string
String temp = text;
// convert text to lowercase
temp = temp.toLowerCase();
// split tokens by one or more spaces
String [] tokens = temp.split(" +");
int j;
int numCount = 0;
double total = 0;
int sentCount = 0;
for (j=0;j<tokens.length;j=j+1)
{
// check to see if token ends with a comma
if (tokens[j].endsWith(",")==true)
{
// get rid of the comma
tokens[j]=tokens[j].replaceAll(",","");
}
// otherwise check to see if it ends with a period
else if (tokens[j].endsWith("."))
{
tokens[j]=tokens[j].replaceAll("\\.","");
sentCount = sentCount + 1;
}
if (tokens[j].matches("-?[0-9]+|-?[0-9]*\\.[0-9]+"))
{
System.out.println(" Number found: " + tokens[j]);
numCount++;
// Convert number into a Double
double num = Double.parseDouble(tokens[j]);
total = total + num;
}
if(tokens[j].startsWith("a"))
{
// Print that token and count it
System.out.println("Word starts with a: "+tokens[j]);
}
}
System.out.println("Sum of the 3 three numbers: " + total);
System.out.println((tokens.length - numCount) + " words");
System.out.println(sentCount +" sentences" );
// main
}
// class
}
Код продолжает отображаться так:
Word starts with a: a
Number found: 100
Number found: 34.0
Number found: 21
Word starts with a: and
Word starts with a: are
Word starts with a: and
Word starts with a: also
Word starts with a: are
Word starts with a: also
Word starts with a: are
Word starts with a: and
Word starts with a: all
Word starts with a: and
Word starts with a: all
Word starts with a: a
Word starts with a: and
Word starts with a: an
Sum of the 3 three numbers: 155.0
71 words
4 sentences
Поэтому мой вопрос заключается в том, как сделать так, чтобы первая строка отображения оставалась с остальной частью «Слово начинается с:». Когда я попытался добавить «Слова, заканчивающиеся на s:», оно смешалось сдругие разделы. Любая помощь будет принята с благодарностью.