s I'm having a problem with this program. The user will enter a keyword, and then after that will enter a sentence. I need the program to output how many sentences contain the keyword, and the average starting position of the keyword in the strings. This is what I have so far. Whenever the program outputs, it doesn't give me the correct # of times the keyword is entered. It just gives me the # of sentences. Can somebody please help me? Thanks.
import java.util.Scanner;
public class Lab6Loops {
public static void main(String[] args) {
String keywordString;
String inputString;
Scanner keyboard = new Scanner (System.in);
int numofSentences = 0;
int numofKeyword = 0;
System.out.println ("Enter a keyword. We will search each sentence for this word.");
keywordString = keyboard.nextLine ();
System.out.println ("Please enter a sentence or type 'stop' to finish");
inputString = keyboard.nextLine ();
while( !inputString.equals ("stop"))
{
if(inputString.contains (inputString));
numofSentences = numofSentences + 1;
if(inputString.contains (keywordString));
numofKeyword = numofKeyword + 1;
System.out.println ("Enter a line of text or 'stop' to finish");
inputString = keyboard.nextLine();
}
System.out.println ("You entered " + numofSentences + " sentences");
System.out.println ("You have " + numofKeyword + "sentences that contain the keyword");
}
}
解决方案
Maybe without the ; after the if statements it will work better :-)
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter a keyword. We will search each sentence for this word.");
String keywordString = keyboard.nextLine();
System.out.println("Please enter a sentence or type 'stop' to finish");
String inputString = keyboard.nextLine();
int numofSentences = 0;
int numofKeyword = 0;
while (!inputString.equals("stop"))
{
if (inputString.contains(inputString))
numofSentences++;
if (inputString.contains(keywordString))
numofKeyword++;
System.out.println("Enter a line of text or 'stop' to finish");
inputString = keyboard.nextLine();
}
System.out.println ("You entered " + numofSentences + " sentences");
System.out.println ("You have " + numofKeyword + "sentences that contain the keyword");
}