User Input not working with keyboard.nextLine() and String (Java)

后端 未结 7 587
耶瑟儿~
耶瑟儿~ 2020-12-22 03:06

I recently started learning java during my spare time. So to practice, I\'m making a program that takes a temperature (Celsius or Fahrenheit) and converts it to the opposite

相关标签:
7条回答
  • 2020-12-22 03:39

    Never use Scanner#nextLine after Scanner#nextInt. Whenever you hit enter button after Scanner#nextInt than it will skip the Scanner#nextLine command. So, Change from

     int temp = keyboard.nextInt();
    

    to

     int temp = Integer.parseInt(keyboard.nextLine());
    
    0 讨论(0)
  • 2020-12-22 03:39

    You could use keyboard.next() instead of nextLine() and as

    user1770155

    mentioned to compare two strings you should use .equals() and what I would do since you're comparing to an upper letter "C" is

     type = keyboard.next().toUpperCase();
    
    
    
    if (type.equals("C"))
    
    0 讨论(0)
  • 2020-12-22 03:46

    Use Scanner Class:

    int temp;
    java.util.Scanner s = new java.util.Scanner(System.in);
    String opposite, type;
    double product;
    
    System.out.print("Please enter a temperature: ");
    temp = s.nextInt();
    
    System.out.println("Was that in Celsius or Fahrenheit?");
    System.out.print("(Enter 'C' for Celsius and 'F' for Fahrenheit) ");
    type = s.nextLine();
    
    if (type.equals("C")){
    do something
    }
    else{
    do something
    }
    

    For More Input references:

    Scanner

    BufferedReader

    String

    Here is a wonderful comparison on how to compare strings in java.

    0 讨论(0)
  • 2020-12-22 03:48

    .nextInt() does not read the end of line character "\n".

    You need to put a keyboard.nextLine() after the .nextInt() and then it will work.

    0 讨论(0)
  • 2020-12-22 03:49

    Also, use type.equals("C") instead of if (type == "C"), the later one is comparing the reference of the value.

    0 讨论(0)
  • 2020-12-22 03:52

    For you code Change nextLine(); to next(); and it will work.

    System.out.println("Was that in Celsius or Fahrenheit?");
        System.out.print("(Enter 'C' for Celsius and 'F' for Fahrenheit) ");
        type = keyboard.next();
    

    to get an idea for you to what happened was this:

    • nextLine(): Advances this scanner past the current line and returns the input that was skipped.
    • next(): Finds and returns the next complete token from this scanner.

    Also like the many of the answers says use equals() instead of using ==

    The == checks only the references to the object are equal. .equal() compares string.

    Read more Here

    0 讨论(0)
提交回复
热议问题