2016-11-06 79 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?