Comparing a Scanner to a String - java

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.

Related

Boolean method with an incorrect input

I'm a bit stuck on an exercice I have to make and I can't figure out the best way to do it.
I have to make a method that asks a question and expects Y or N. So I thought I would make a boolean method to return true or false, but the problem is that it would also return false if the user puts something other than Y or N. If I'm not mistaken, a boolean method cannot return null.
I'm very new to java and I'm not very far in my course so this problem will probably have a very simple solution. I also tried looking for an answer but didn't seem to find what I was looking for.
This is what I have with the boolean method but i'm not quite happy with it:
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
if (reponse.equalsIgnoreCase("Y")) {
return true;
}
else if (reponse.equalsIgnoreCase("N")) {
return false;
}
else {
return false;
}
}
You need only one condition equalsIgnoreCase("Y"), result of its evaluation is basically the return value. All the if-statements in your code are redundant.
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
return reponse.equalsIgnoreCase("Y"));
}
Going by your comment you want your program to ask for input again if the input is neither "y" nor "n". You can achieve that behavior by adding an extra loop:
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String response = sc.next();
while(!response.equalsIgnoreCase("Y") && !response.equalsIgnoreCase("N")) {
// loop as long as input is neither "y" nor "n" (ignoring case)
System.out.println("Please enter 'y' or 'n'");
reponse = sc.next();
}
// if the loop is done input has to be either "y" or "n" at this point
return reponse.equalsIgnoreCase("y");
}
The problem is at the end you are explicitly telling java to return false when neither a Y or N is entered. I would try putting in another else statement to have the user re-enter the data or just notify them that they have entered the wrong value.
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
while(!response.equalsIgnoreCase("Y") ||!response.equalsIgnoreCase("N"){
#Do something here until
the user inputs the correct value.
}
}

Is there a way to write this program using another method than .hasNext?

Write a program that asks a user to input a string. Then asks a user to type in an index value(integer). You will use the charAt( ) method from the string class to find and output the character referenced by that index. Allow the user to repeat these actions by placing this in a loop until the user gives you an empty string. Now realize that If we call the charAt method with a bad value (a negative value or a integer larger than the size of the string) an exception will be thrown. Add the code to catch this exception, output a warning message and then continue with the loop
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
System.out.println("");
String s;
int ind;
Scanner sc=new Scanner(System.in);
while(sc.hasNext())
{
s=sc.next();
if(s.length()==0)
break;
ind=sc.nextInt();
try {
char ch=s.charAt(ind);
System.out.println("Character is "+ch);
}
catch(Exception e) {
System.out.println("Bad index Error!");
}
}
}
}
Yes. You could rely on assignment evaluating to the assigned value. Also, call Scanner.hasNextInt() before calling Scanner.nextInt(). Like,
System.out.println();
String s;
Scanner sc = new Scanner(System.in);
while (sc.hasNext() && !(s = sc.next()).isEmpty()) {
if (sc.hasNextInt()) {
int ind = sc.nextInt();
try {
char ch = s.charAt(ind);
System.out.println("Character is " + ch);
} catch (Exception e) {
System.out.println("Bad index Error!");
}
}
}
There is a bug; sc.next() cannot return an empty string in this code. Try editing it this way:
while(sc.hasNext()) {
s = sc.next();
if(s.length() == 0) {
System.out.println("Woah, Nelly!");
break;
}
// ...
}
See if you can get the program to print "Woah, Nelly!" by entering a blank line, or anything else. I can't, and assuming I understand the documentation correctly, it is impossible for the if condition to ever be true here (emphasis mine):
Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern "\\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern "\s" could return empty tokens since it only passes one space at a time.
This pattern "\\s+" is the default one, and you haven't set a different one, so your scanner should never return an empty token. So the strict answer to "is there a way to write this program without the break statement?" is: yes, you can just delete the if(...) break; code and it doesn't change the behaviour in any way.
However, that's not really a solution to your problem because it doesn't give the user a way to exit the program. You should use nextLine() instead of next() to allow reading a blank line from the user.

Taking websites as keyboard input?

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?

Stuck on how to make string character input only

for the last few hours i've been trying to get this code to only allow character input, as its for accepting names..
I have been following the same type of method i used to allow only integers, but with no luck.
any advice would be great,
Here is my code
String name;
System.out.println("Enter student's name: ");
name = in.nextLine();
while (!in.nextLine().matches("[a-zA-Z]"));
{
System.out.println("Please enter a valid name!: ");
in.next();
}
name = in.nextLine();
Your regex checks if the line matches exactly one [a-zA-Z] character. You probably want to check at least one: [a-zA-Z]+
Bear in mind that the way you are checking, you won't get what you have checked in the variable name, as you are consuming it in your checking. Can I propose an alternative:
System.out.println("Enter student's name: ");
String name = in.nextLine();
while(!name.matches("[a-zA-Z]+")){
System.out.println("Please enter a valid name!");
name = in.nextLine();
}
I'm not too familiar with regex, personally, so I would just go with a method that takes a string and determines whether it is only comprised of the alphabets.
[EDIT] Shame on me, the method for testing if a character is a letter is static. Thanks to dansalmo for reminding me.
public static boolean isAlphabetic(String s) {
for(int i = 0; i < s.length(); i++) {
if (!Character.isLetter(s.charAt(i))) return false;
}
return true;
}
Did you check the value of the variable name?
While you assign the input to name , you seem to read the next line for regex check.
Remove the in.next too and it should work fine
Similar to Bucco's solution but iterating over a char array:
public static boolean isAlphabetic(String s) {
for(char c : s.toCharArray())
if (!Character.isLetter(c)) return false;
return true;
}

Java input failure [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
What am I doing wrong? After I compile and run the program, I type in my input and no matter what it is, the program always takes it as an incorrect input and says I'm wrong, here:
import java.util.Scanner;
public class mena3 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String Capitol;
System.out.print("Enter the capitol of Morocco: ");
Capitol = user_input.next();
if(Capitol == "Rabat") {
System.out.println("Good Job!");
}
else {
System.out.println("That is incorrect");
}
}
}
And after I put in Rabat, it says That is incorrect. If I put in l, it says That is incorrect. Why can't I win?
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}
Voting to close this question as it's only been asked and answered umpteen million times on this site.
One of the most common mistakes in java. String require a .equals() rather than an ==.
Wrong:
if (str == "foo") {
}
Right:
if ("foo".equals(str)) { // done in this order to avoid NPE
}
Your code is perfect, only your comparison method is wrong. All other languages treats == as comparison operator. But in case of Java it is little bit tricky. Here in Java == is taken as comparison operator for objects, not a string variable.
So, to compare two Strings you have a method called `.equals() which is from String class it self.
hence you need to change your code accordingly,
import java.util.Scanner;
public class mena3
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
String Capitol;
System.out.print("Enter the capitol of Morocco: ");
Capitol = user_input.next();
// if(Capitol == "Rabat") // your previous code
if(Capitol .equals ( "Rabat") ) // new updated comparison code
{
System.out.println("Good Job!");
}
else
{
System.out.println("That is incorrect");
}
}
}

Categories