2016-11-06 74 views
0

下面是我给出的问题: 编写一个程序,将网站名称当作键盘输入,直到用户键入单词“stop”。程序m也计算有多少网站名称是商业网站名称(即以.com结尾),并输出该数量。将网站作为键盘输入?

即使我输入“stop”作为输入,仍然存在的问题仍然是“输入下一个站点”。我不确定我出错的地方。

任何人都可以帮忙吗?这是我的代码。

import java.util.Scanner; 


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

{ 

    int numberOfComSites = 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 (website != SENTINEL) 
    { 
     if(substring == commercialNames) 
     { numberOfComSites++; 
     } 
     System.out.print("Enter the next site > "); 
     website = scan.next(); 
    } 

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




} 

谢谢!

回答

0

您正在使用引用相等==比较字符串。你的字符串来自不同的来源。 SENTINEL来自常量池,而website来自用户输入。它们通常与参考文献不同。

要按值比较字符串,应使用equals方法。在你的情况,应该由我们比较了用户输入恒定

while (!SENTINEL.equals(website)) 

通知更换

while (website != SENTINEL) 

。这在websitenull时解决了一个问题。这不是你的代码的情况,但它是一个好风格的标志。

请参阅What is the difference between == vs equals() in Java?了解更多信息。

0

while(!website.equals(SENTINEL)) 

websiteString是型,并且不是原始类型替换

while (website != SENTINEL) 

。所以你需要使用equals方法来比较String==用于参考比较。

请参阅此了解更多详情What is the difference between == vs equals() in Java?