0

Here is the problem I was given: Write a program that takes website names as keyboard input until the user types the word 'stop'. The program m just also count how many of the website names are commercial website names (i.e., end with .com), and output that count.

The problem that keeps occurring is even if I type the word stop as input, it is still saying to "enter the next site." I'm not sure where I went wrong.

Can anyone help? Here is my code.

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




}

Thanks!

A. Moore
  • 53
  • 2
  • 7

2 Answers2

0

replace

while (website != SENTINEL)

with

while(!website.equals(SENTINEL))

website is of String type and is not a primitive type. So you need to use equals method to compare String. == is used for reference comparison.

Refer this for more details What is the difference between == vs equals() in Java?

Community
  • 1
  • 1
Johny
  • 2,128
  • 3
  • 20
  • 33
0

You are using reference equality == to compare strings. You strings are from different sources. SENTINEL comes from constant pool, while website comes from user input. They are always different as references.

To compare strings by value, the equals method should be used. In your case you, should replace

while (website != SENTINEL)

by

while (!SENTINEL.equals(website))

Notice that we compares constant with user input. This address a problem when website is null. This is not the case in your code, but it is a sign of good style.

See What is the difference between == vs equals() in Java? for more information.

Community
  • 1
  • 1
kgeorgiy
  • 1,477
  • 7
  • 9