java 循环关键字,Java循环关键字包含

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");

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值