Scanner.equals() returns false in either case

一笑奈何 提交于 2021-02-17 04:08:38

问题


package harry;

import java.util.Scanner;

public class harry {

    public static void main(String[] args) {    

        String Harr = ("Harry");

        Scanner name = new Scanner(System.in);  

        System.out.println("Enter your name");  

        name.nextLine();

        if(name.equals("Harry")) {

            System.out.println("She hates you");    

        } else if (name.equals("Nick")) {

            System.out.println("She loves you");    
        }

    }

}

In this code, I am trying to write the following:

  • If the name is “Harry”, it should print “She hates you”
  • If the name is “Nick”, it should print “she loves you”

However, when I write either one of these names, it doesn’t print anything.


回答1:


Scanner is used a little differently :

package harry;

import java.util.Scanner;

public class harry {

    public static void main(String[] args) {    

        String Harr = ("Harry");

       Scanner input = new Scanner(System.in);   

        System.out.println("Enter your name");  

           String name = input.nextLine();

    if(name.equals("Harry")) {

            System.out.println("She hates you");    

        } else if (name.equals("Nick")) {

            System.out.println("She loves you");    
        }

    }

}



回答2:


Try this Nick Nicholas it works when I try:

import java.util.Scanner;

public class harry {

    public static void main(String[] args) {    

        String Harr = ("Harry");

        String s;

       Scanner name = new Scanner(System.in);   

        System.out.println("Enter your name");  

           s = name.nextLine();

    if(s.equals("Harry")) {

            System.out.println("She hates you");    

        } else if (s.equals("Nick")) {

            System.out.println("She loves you");    
        }

    }

}



回答3:


Assign the value of name.nextline to a string and then do the conditional check

The code will be like:

    String n= name.nextLine();

    if(n.equals("Harry")) {

        System.out.println("She hates you");    

    } else if (n.equals("Nick")) {

        System.out.println("She loves you");    
    }


来源:https://stackoverflow.com/questions/29255542/scanner-equals-returns-false-in-either-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!