2016-11-07 222 views
0

下面是我给出的问题: 编写一个程序,将网站名称当作键盘输入,直到用户键入单词“stop”。该程序还必须计算有多少网站名称是商业网站名称(以.com结尾)并输出该数量。为什么count ++不能在我的代码中工作?

这是我一直遇到的问题:例如,如果我输入'facebook.com','google.com'和'pintrest',输出将会说我输入了三个商业网站,即使只有两个我输入的网站以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); 

该变量只被设置一次。当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(); 
} 
相关问题