Taking websites as keyboard input? - java

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!

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.

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?

Related

Validating a single character JAVA

I'm trying to make my program validate between the use of two single characters that are input by the user, which must be A or M.
Here's my code I have thus far:
static char getCustomerType() {
System.out.println("Please enter the term for the Policy the client would like");
System.out.println("A for Annual or M for Monthly. Annual provides the user with a 10% discount");
String s = inputs.next();
while (s != 'A' && s != 'M') {
System.out.println("Incorrect, please try again");
s = inputs.next();
}
}
Netbeans however, does not like this stating the inputs.next is never used when I have set it to be used before the while statement?
It also doesn't like the while statement producing incompatible string type referencing boolean to string.
I assume this is because I have declared s as a String?
You can have single characeter input from user using below code assuming inputs is your scanner object:
char c = inputs.next(".").charAt(0);
and then you can compare it using != or .equals() or .equalsIgnoreCase()
why not write
while ( ("A".equalsIgnoreCase(s) || "M".equalsIgnoreCase(s)) == false)

How to use indexOf? Please help a beginner out

So I want to know what indexOf() does. As I want to use it in my program it find out how many vowels are in a word that the user inputs.
public static boolean methodCheck(char a){
return "AEIOUaeiou".indexOf(a) != -1;
}
But that doesnt seem to work at all hahah. as I have no idea what indexOf() actually does. anyway here is my program so far(sorry if its bad I'm really new). I left 5 questions too that would help me a lot! please and thank you for your help :D
import java.util.Scanner;
public class vowelCounter {
private static String input = methodInput(); //1. is there any other way to make a global Scanner?
public static void main(String[] args){
System.out.println("Enter word");
System.out.println(input);
System.out.println("This word has" + methodCheck('a')); //2. what should i put in my parameters?
}
public static boolean methodCheck(char a){
return "AEIOUaeiou".indexOf(a) != -1; //3. what does this line do?
}
public static String methodInput(){
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
return input;
//4. the output is 'hastrue' why is that?
//5. how can i make this program better?
}
}
If you don't know what a method does, then the solution is to go look at what it does. For example, the java documentation will tell you that
public int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character
In either case, if no such character occurs in this string, then -1 is returned.
How you're using it is not necessarily wrong, considering how the method returns -1 if the character wasn't found. But if you want to check how many vowels there are in a word that the user enters, it wouldn't be right to check whether the word they entered is in the string of vowels.
All the standard Java libraries, classes and methods have Javadoc that describes what they do.
All you need to do is look up the Javadoc and they describe it.
In this case the Javadoc is at: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)
Your first step with any question like this should always be the documentation, then if that doesn't work try doing a web search looking for examples. For example 5 seconds on google putting in "java indexOf example" found me:
http://www.tutorialspoint.com/java/java_string_indexof.htm
Then if that doesn't work you can try asking the question here.
When you have the word boolean before the name of a method, that means that the method will return either the value true or the value false. And it's this true or false value that your program is printing out, on the same line as "This word has".
This particular method will return true if the character you pass to it is a vowel, or false otherwise. The method indexOf tells you which character of a String is the first one that is equal to the value that you pass in to the method. It returns 0 for the first character, 1 for the second character and so on. It returns -1 if none of the characters match. In this case, you're just checking whether the value returned by indexOf is or isn't -1 - in other words, whether the character is or isn't in the String "AEIOUaeiou".
indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. If no such value of str exists, then -1 is returned.
For examples :
int num1 = "AEIOUaeiou".indexOf("a"); // it gives 5
int num2 = "AEIOUaeiou".indexOf("A"); // It gives 0
int num3 = "AEIOUaeiou".indexOf("z"); // It gives -1
1 Don't do that! Create a scanner in main, read input with it and then call your method(s).
2 How about countVowels(input)? You'd need to write an static int countVowels(String input) method.
3 Returns true since you pass in 'a'.
4 See number 3.
5 See number 2, and add a static boolean isVowel(char a).
Here is what the indexOf method does
string.indexOf(searchvalue,start)
Parameters
searchvalue : Required. The string to search for
start : Optional. Default 0. At which position to start the search
Return Value
Number : The position where the specified searchvalue occurs for the first time, or -1 if it never occurs
In simple terms, the index of method checks the first occurence of the value passed to it from the start position(if specified) and returns the position at which the value was first encountered in the string.
eg.
String s = "AEIOUaeiou";
s.indexOf("a"); //This would get a value of 5.
s.indexOf("v"); //This would get a value of -1, since it doesn't have the character v
To answer your questions,
You can directly declare the scanner as private and use it in the
entire program
`private static Scanner input = new Scanner(System.in);`
you can write a method that receives the String input by the user
and then checks if the String contains any of the vowels. You can
use indexOf or contains methods to check for the each vowel using
the indexOf method.
Already described above.
A better way to do it would be as follows.
public class vowelCounter{
public static void main (String[] args) {
Scanner keyboard = new Scanner (System.in); // No need to declare it as global. You use it only once.
System.out.println ("Enter word : "); //Prompt the user to enter a word
String input = keyboard.nextLine (); //Fetch the word that the user enters into a String
System.out.println ("This word has" + countVowel (input)); // Pass the string to the method to check if it has vowels.
}
private static int countVowel (String a) {
int count = 0;
String s = a.toLowerCase (); // convert the string to lower case so that you only have to check for the lower case characters
// Here you would need to check the number of times each vowel exists in the String and incremenet the count everytime.
return count;
}
}

Is it possible to only check the first four letters of a string during: input.equals("USER test"); JAVA POP3

I'm trying to make a mail system with POP3 commands using java.
When a user logs in, they enter "USER" followed by their username e.g "USER ben"
in order to send them along their way I was wondering if here:
import java.util.Scanner;
public class TestingPart1 {
public static void main(String[]args){
int on = 1;
while (on == 1){
System.out.println("+OK POP3 server ready");
Scanner answer = new Scanner(System.in);
String Input = answer.nextLine();
**if (Input.equals.("USER test")){
CommandInterpreter.handleUser(Input);
}**
I would be able to only check the first four characters USER so that when it gets passed through to CommandInterpreter it still reads USER test, but passes this stage
thanks :)
if (Input.startsWith("USER ")) { ...
You can use a split with a space into a string array. Then evaluate whether the first element of the array is equal to "USER"
Input is unchanged by the split operation.

Comparing a Scanner to a String

I'm trying to ask the user to enter a character ("y"/"n") and check whether or not that was the right answer. I'm getting the following error: "incomparable types: java.util.Scanner and java.lang.String"
Scanner userInput = new Scanner(System.in);
System.out.printf("Is this word spelled correctly?: %s", wordToCheck);
rightCheck(userInput);
public boolean rightCheck(Scanner usersAnswer)
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
Yes, because a scanner is a way of getting input rather than the value itself. You want to fetch the next value from the input, and then compare it. Something like this:
String answer = scanner.next();
if (answer.equals("y")) {
...
} else if (answer.equals("n")) {
...
}
Note that you should usually (including this case) not compare strings with ==, as that compares whether the two operands refer to the exact same string object - you're only interested in whether they refer to equal objects. (See this question for more details.)
I have modified your code, haven't tested it but it should work:
Scanner userInput = new Scanner(System.in);
System.out.println("Is this word spelled correctly?:" + wordToCheck);
rightCheck(userInput.next());//send the string rather than the scanner
public boolean rightCheck(String usersAnswer)//convert the parameter type to String
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
I believe you should first get the String from Scanner (through next() maybe?). Then in your method, do not use "==" as a string comparator.

"Incompatible operand types int and string"

I just started learning code (Java specifically), and i'm testing out a password system where when you type the password it becomes the variable "password" and it checks to see if it equals password2, the actual password. Here's the code:
import java.util.Scanner;
public class LogicalOperators {
public static void main(String args[]){
Scanner test = new Scanner(System.in);
int age;
int password;
String password2;
password2 = "Call of Duty";
System.out.println("Please enter your age:");
age = test.nextInt();
if (age >=18) {
System.out.println("You are old enough.");
System.out.println("Please enter the password:");
password = test.nextInt();
if (password == password2) {
System.out.println("Welcome back!");
}else{
System.out.println("The password you typed was incorrect.");
}
}else{
System.out.println("You are too young.");
}
}
}
I'm trying to check in the nested if statement whether the password I typed in matched password2, "Call of Duty"; but the problem is that it doesn't work with strings. The title of this question is the error that comes up. Can someone please help me?
I try to give a hint instead of providing the full answer:
Check the data types of password and password2. Why are they different?
when comparing strings you should use equals instead of ==
So use
if(password.equals(password2){
do something
}
You have to make a couple of changes.
First password should be of type String since you want to store a string here and compare it with another string.
Next, just after age = test.nextInt();, you should do a test.nextLine() to consume the newline at the end of the input. We don't want to read this when we read the password.
Next, you should use password = test.nextLine(); to read the password entered by the user.
Lastly, you should compare it using: if (password.equals(password2)). == compares whether both the String objects have the same references, i.e., whether they are the same String objects as known to Java. You want .equals() here because it would compare whether the content of the two String objects are equal. In this case, password and password2 refer to two different String objects which may have the same content.

Categories