简体   繁体   中英

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!

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

    }
String substring = website.substring(website.length()-3);

That variable is only being set once. You're not recomputing it when website changes.

Your substring is in the wrong place. You initialize it once for the first entry and then forget to change it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM