2016-11-07 12 views
0

ここに私が与えられた問題があります: ユーザーが単語「停止」をタイプするまでキーボード入力としてウェブサイト名を取るプログラムを書く。このプログラムでは、商用のウェブサイト名(.comで終わる)のウェブサイト名の数を数え、その数を出力する必要があります。私のコードでcount ++が動作しないのはなぜですか?

私は「facebook.com」、「google.com」、「pintrest」と入力した場合、出力には3つの商業用サイトが入力されたと表示されます。私の入力サイトはcomで終わります。 誰かが私が間違っていた場所を説明することができますし、どのようにそれを修正するための最良の方法はありますか?ここに私のコードです。

import java.util.Scanner; 


public class NewClass 
{ 
public static void main(String [] args) 

{ 

    int count = 0; 
    String commercialNames = "com"; 
    final String SENTINEL = "stop"; 
    String website; 

    Scanner scan = new Scanner(System.in); 
    System.out.print("Enter a website, or 'stop' to stop > "); 
    website = scan.next(); 

    String substring = website.substring(website.length()-3); 

    while (!SENTINEL.equals(website)) 

    { 
     if(substring.equals(commercialNames)) 
     { 
      count++; 
     } 
     System.out.print("Enter the next site > "); 
     website = scan.next(); 
    } 

     System.out.println("You entered " + count + " commercial websites."); 
     } 




} 

ありがとう!

+0

大変申し訳ございません。私は初心者です。私は間違って私の質問に言い聞かせた場合私は謝罪:) –

答えて

2

新しい入力websiteを受け取った後に、変数substringを割り当てる必要があります。したがって、それはする必要があります

String substring; 
while (!SENTINEL.equals(website))  
    { 
     substring = website.substring(website.length()-3); 
     if(substring.equals(commercialNames)) 
     { 
      count++; 
     } 
     System.out.print("Enter the next site > "); 
     website = scan.next(); 

    } 
0
String substring = website.substring(website.length()-3); 

この変数は1回だけ設定されています。 websiteが変更されたときには再計算しません。

0

あなたの部分文字列が間違った場所にあります。最初のエントリに対して一度だけ初期化してから、変更を忘れてしまいます。

while (!SENTINEL.equals(website)) 

{ 
    String substring = website.substring(website.length()-3); 
    if(substring.equals(commercialNames)) 
    { 
     count++; 
    } 
    System.out.print("Enter the next site > "); 
    website = scan.next(); 
} 
関連する問題