A. Moore A. Moore - 27 days ago 13
Java Question

Why is count++ not working in my code?

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

Here is the problem I keep running into: for example, if I input 'facebook.com', 'google.com', and 'pintrest' the output will say I entered three commercial sites, even though only two of my inputed sites end with com.
Can someone explain where I went wrong and how is the best way to fix it? Here is my code.

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




}


Thanks!

Answer

You must assign variable substring after you take the new input website. So, it should be

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();

    }
Comments