2012-04-01 38 views
-1

可能重复:
Loop Keyword Program HomeworkJava循环关键词含

了,我就是有这个程序有问题。用户将输入一个关键字,然后再输入一个句子。我需要程序输出多少句子包含关键字,以及关键字在字符串中的平均起始位置。这是我迄今为止所拥有的。只要程序输出,它不会给我输入关键字的正确次数。它给我的句子#。有人能帮帮我吗?谢谢。

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"); 
    } 
} 
+0

你从读者期待什么好?整个解决方案都为您烹制或修复了一个您无法找到的错误?请确切说明你的期望。 – Vincent 2012-04-01 06:22:13

+0

我希望有人能够向我解释我在做什么错误,导致输出不能正确保留包含用户输入关键字的句子数。我对Java真的很陌生,所以我知道这是初学者的东西。 – user1276514 2012-04-01 06:24:46

+3

不要在你的if语句头后放置分号:'if(inputString.contains(inputString)); < - no';'' – 2012-04-01 06:30:15

回答

2

也许没有;if报表后,将工作:-)

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"); 
} 
+0

哇,这是我第二次犯这个错误,而且在追踪时我甚至没有注意到它。感谢Vincent的帮助。 现在为第三部分。 我需要找到关键字的平均起始位置,但只能在包含关键字的句子中找到。所以如果声明,输入字符串包含关键字字符串 如何输出indexOf的keywordString? – user1276514 2012-04-01 06:35:21

+0

不客气。不要忘记将正确的答案标记为本网站的解决方案。谢谢。 – Vincent 2012-04-01 06:39:09