Skip If statement

import java.util.Scanner;

public class Questionaire {

  public static void main(String[] args) {

    String name;
    String ansOne;
    Scanner input = new Scanner(System.in);

    System.out.print("Hello, welcome to the super awesome quiz. Let get things going. What is your name?");
    name = input.nextLine();
    System.out.print("Okay, hi " + name + " I'm just going to call you Bob.");
    System.out.print(" Question 1: What is the name of your dog?");
    ansOne = input.nextLine();

    if (ansOne == "Avagantamos") {
      System.out.print("Correct!");
    } else {
      System.out.print("Wrong! The correct answer was Avagantamos!");
    }

  }
}

      

So, basically, when it asks you to enter your dog's name, it is always wrong, even when you type Avagantamos. I'm still actually a noob and it was very frustrating, which is why I thank so much everyone who answers.

+3


source to share


4 answers


Don't use ==

for string comparison. Use the equals(...)

or method equalsIgnoreCase(...)

.

Understand what is ==

checking if the two objects are the same, which you are not interested in. Methods, on the other hand, check if two strings have the same characters in the same order, and what's important here. Therefore, instead of

if (fu == "bar") {
  // do something
}

      

do,



if (fu.equals("bar")) {
  // do something
}

      

or,

if (fu.equalsIgnoreCase("bar")) {
  // do something
}

      

+9


source


Use String.compareTo()

(or String.equals())

instead of==



+2


source


When comparing strings, use .equals()

rather than ==

. This is because it ==

compares objects according to the reference id, and there may be multiple instances String

that contain the same data. The method .equals()

will compare the contents of String

s which you want. Therefore, you must write

 if (ansOne.equals("Avagantamos")) {

      

In this case, it seems to be input.nextLine()

creating a new object String

, so ==

doesn't work.

By the way, you probably wanted to use System.out.println

, not .print

; otherwise, prompts and output will run together on the same line.

+2


source


Use ansOne.equals("Avagantamos")

==

compares object references.

+1


source







All Articles